今天在寫線程測試的時候,寫下了以下的一段代碼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"); } } }