今天在写线程测试的时候,写下了以下的一段代码ide
public class ThreadTests { [@Test](https://my.oschina.net/azibug) public void test_thread_sleep() throws InterruptedException { Thread t = new Thread(new MyRunnable()); t.start(); t.sleep(10000); while(true) System.out.println("main thread"); } public class MyRunnable implements Runnable{ [@Override](https://my.oschina.net/u/1162528) public void run() { System.out.println("son thread"); } }
}测试
结果测试以后,并无按照我预想的那样执行。即打印 10 s的 “main thread”,而后打印出 “son thread”。 而实际执行结果是主线程阻塞了 10s,而后一直打印 “main thread”。.net
sleep() 方法 是 Thread 类中的一个静态方法,跟调用他的对象无关,而是跟在哪一个线程调用他有关系,所以在主线程调用 t.sleep(); 方法实际上等于调用 Thread.sleep() 。同时也就形成主线程阻塞 10 s。线程
从上面的分析中能够得出以下用法:code
public class ThreadTests { [@Test](https://my.oschina.net/azibug) public void test_thread_sleep() throws InterruptedException { Thread t = new Thread(new MyRunnable()); t.start(); //t.sleep(10000); while(true) System.out.println("main thread"); } public class MyRunnable implements Runnable{ [@Override](https://my.oschina.net/u/1162528) public void run() { try { Thread.currentThread().sleep(10);// 在子线程的 run() 方法里调用sleep() 方法 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("son thread"); } } }