java - wait(),notify(),notifyAll() T2 start! T2 end! T1 start! 為什么會阻塞
問題描述
public class Thread04 { final Object object = new Object();Runnable rb4 = new Runnable() { public void run(){synchronized (object){System.out.println('T1 start!');try { object.wait();} catch (InterruptedException e) { e.printStackTrace();}object.notify();System.out.println('T1 end!'); }}};Runnable rb5 = new Runnable() { public void run(){synchronized (object){ System.out.println('T2 start!'); object.notify(); System.out.println('T2 end!'); }}};public static void main(String[] args) {Thread04 th = new Thread04();new Thread(th.rb4).start();new Thread(th.rb5).start(); } }
問題解答
回答1:rb5 的 object.notify(); 調用時 rb4 還沒有進入 wait 狀態,因為還在等待鎖。線程 start 并不代表馬上會自行 run(),也就是說后 start() 的線程的 run() 很有可能先執行。
回答2:rb4在運行獲得object的對象鎖,輸出T1 start!,然后調用wait(),該方法會讓rb4掛起,同時釋放鎖,阻塞。 這時候rb5獲得鎖,輸出T2 start!。然后調用object.notify();,雖然這里打算讓rb4運行,但是rb5的鎖并沒有釋放,所以rb4還是處于阻塞。 rb5還是繼續運行,輸出T2 end!。 rb5運行結束,釋放鎖, rb4運行輸出T1 end!。
相關文章:
