輸出結果:main start t1 -> main wait() -> t1 call notify() -> main continue 其實調用t1.start(),t1為就緒狀態,只是main方法中,t1被main線程鎖住了,t1.wait()的時候,讓當前線程等待,其實是讓main線程等待 ...
class ThreadA extends Thread{ public ThreadA(String name) { super(name); } public void run() { synchronized (this) { System.out.println(Thread.currentThread().getName()+" call notify()"); notify(); } } } public class WaitTest { public static void main(String[] args) { ThreadA t1 = new ThreadA("t1"); synchronized(t1) { try { // 啟動“線程t1” System.out.println(Thread.currentThread().getName()+" start t1"); t1.start(); // 主線程等待t1通過notify()喚醒。 System.out.println(Thread.currentThread().getName()+" wait()"); t1.wait(); System.out.println(Thread.currentThread().getName()+" continue"); } catch (InterruptedException e) { e.printStackTrace(); } } } }
輸出結果:main start t1 -> main wait() -> t1 call notify() -> main continue
其實調用t1.start(),t1為就緒狀態,只是main方法中,t1被main線程鎖住了,t1.wait()的時候,讓當前線程等待,其實是讓main線程等待了,然後釋放了t1鎖,t1線程執行,列印t1 call notify(),然後喚醒main線程,最後結束;
這裡說一下wait()與sleep()的區別,他們的共同點都是讓線程休眠,但是wait()會釋放對象同步鎖,而sleep()不會;下麵的代碼t1結束之後才會運行t2;能夠證實這一點;
public class SleepLockTest{ private static Object obj = new Object(); public static void main(String[] args){ ThreadA t1 = new ThreadA("t1"); ThreadA t2 = new ThreadA("t2"); t1.start(); t2.start(); } static class ThreadA extends Thread{ public ThreadA(String name){ super(name); } public void run(){ synchronized (obj) { try { for(int i=0; i <10; i++){ System.out.printf("%s: %d\n", this.getName(), i); // i能被4整除時,休眠100毫秒 if (i%4 == 0) Thread.sleep(100); } } catch (InterruptedException e) { e.printStackTrace(); } } } } }