java - 關于多線程notify的問題
問題描述
public class WaitTest { static class ThreadA extends Thread {public ThreadA(String name){ super(name);}@Overridepublic void run() { synchronized (this){ System.out.println(Thread.currentThread().getName()+' call notify()'); //notify();//notify之后 要等到這個代碼塊結束之后才會把鎖讓出去,當然如果在notify之后又有wait,那就會主動把鎖讓出去 try { System.out.println(Thread.currentThread().getName()+' wait'); //wait(); //Thread.sleep(10000); } catch (Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+' after notify'); }} } public static void main(String[] args) throws InterruptedException {ThreadA t1 =new ThreadA('t1');synchronized (t1){ System.out.println(Thread.currentThread().getName()+' start t1'); t1.start(); System.out.println(Thread.currentThread().getName()+' wait'); t1.wait();////System.out.println(Thread.currentThread().getName()+' notify'); // t1.notify(); System.out.println(t1.getName()); System.out.println(Thread.currentThread().getName()+' continue'); //t1.notify();} }}
照理來說 t1.wait() 應該會阻塞主線程,并沒有其他地方notify而去掉t1.start()之后,就能阻塞住了
這是什么道理?編譯器優化?還是synchronized代碼塊內如果不對monitor進行操作,結束主動notify??
問題解答
回答1:并不是優化其實,跟線程的執行有關的。在java doc中,public final synchronized void join(long millis)這個方法的注釋上面寫著一句話
<p> This implementation uses a loop of {@code this.wait} calls conditioned on {@code this.isAlive}. As a thread terminates the {@code this.notifyAll} method is invoked. It is recommended that applications not use {@code wait}, {@code notify}, or {@code notifyAll} on {@code Thread} instances.
看到加黑體,其實是線程結束之后調用的notifyAll導致wait蘇醒的。并不是什么虛擬機優化導致的。希望能解答你的困惑
相關文章:
1. javascript - js 有什么優雅的辦法實現在同時打開的兩個標簽頁間相互通信?2. css3 - 在sublime text里, 如何讓emmet生成的帶前綴css屬性垂直對齊?3. mac連接阿里云docker集群,已經卡了2天了,求問?4. javascript - weex和node,js到底是怎樣一個關系呢?5. javascript - 一個抽獎的效果(如圖)?6. javascript - 這是什么插件能把能把cli里面的webpack打包信息格式化?7. 想找個php大神仿個網站。8. javascript - 怎樣限制同一個瀏覽器不能登錄兩個賬號9. html5和Flash對抗是什么情況?10. javascript - jquery怎么給select option一個點擊時觸發的事件,如圖 如果選擇自定義觸發一個時間?
