Java中线程的休眠(sleep方法)

在程序中要使一个线程休眠,直接使用Thread.sleep()方法即可

1. 方法介绍
 
sleep(long millis) 线程睡眠 millis 毫秒
 
sleep(long millis, int nanos) 线程睡眠 millis 毫秒 + nanos 纳秒

2. sleep方法的使用
 
sleep方法是静态方法,直接使用Thread.sleep()就可以调用
 
在Java中,sleep方法的定义上使用了throws,所以在使用sleep方法时,一定要用try catch。

3. 在何处使用sleep方法?
 
sleep最好使用在run方法的内部,因为写在run方法内部可以让该线程休眠

public class Thread1 {
	public static void main(String[] args) {
		Runner1 r1 = new Runner1();		
		Thread t = new Thread(r1);		
		t.start();
		for (int i = 0; i < 3; i++) {
			System.out.println("main thread :"+i);
		}		
	}
}
 
class Runner1 implements Runnable{
	@Override
	public void run() {		
        try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
        for (int i = 0; i < 3; i++) {
        	System.out.println("Runner1 : " + i);
        }
	}	
}

结果:

main thread :0
main thread :1
main thread :2
-----------------  此处睡眠5秒,5秒后出现以下:
Runner1 : 0
Runner1 : 1
Runner1 : 2

4. sleep究竟是让哪一个线程休眠?

sleep方法只能让当前线程睡眠,调用某一个线程类的对象t.sleep(),睡眠的不是t,而是当前线程。
我们通过继承Thread类创建线程。在Runner1的run()中不写sleep(),在主线程中写Runner1.sleep(5000),结果不是Runner1睡眠,还是主线程睡眠,请看下面输出结果

public class Thread1 {
	public static void main(String[] args) {
		Runner1 r = new Runner1();		
		r.start();
		try {
			Runner1.sleep(5000); //此处是类名.sleep()
			System.out.println("当前运行的线程名称: "+ Runner1.currentThread().getName());      
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		for (int i = 0; i < 3; i++) {
			System.out.println("main thread :"+i);
		}		
	}
}
 
class Runner1 extends Thread{
	public void run() {		
            for (int i = 0; i < 3; i++) {
        	System.out.println("Runner1 : " + i);
            }
	}	
}

结果:

Runner1 : 0
Runner1 : 1
Runner1 : 2
---------------------------------  此处睡眠5秒,5秒后出现以下:
当前运行的线程名称: main
main thread :0
main thread :1
main thread :2

猜你喜欢

转载自blog.csdn.net/weixin_43938560/article/details/89818229