java - 關於多執行緒notify的問題
给我你的怀抱
给我你的怀抱 2017-05-17 10:01:54
0
1
505
public class WaitTest { static class ThreadA extends Thread { public ThreadA(String name){ super(name); } @Override public 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)這個方法的註解上面寫著一句話

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 inis injed inisgended that applications not use {@code wait}, {@code notify}, or {@code notifyAll} on {@code Thread} instances.

看到加黑體,其實是線程結束之後調用的notifyAll導致wait甦醒的。並不是什麼虛擬機器優化導致的。希望能解答你的困惑

    最新下載
    更多>
    網站特效
    網站源碼
    網站素材
    前端模板
    關於我們 免責聲明 Sitemap
    PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!