鍍金池/ 問答/Java  Linux  網(wǎng)絡(luò)安全/ 多線程如何確保在另一個線程的obj.notify()執(zhí)行之前,當(dāng)前線程已經(jīng)執(zhí)行了

多線程如何確保在另一個線程的obj.notify()執(zhí)行之前,當(dāng)前線程已經(jīng)執(zhí)行了obj.wait()?

如果線程的wait比notify先執(zhí)行,那么程序就死了,怎么才能解決這個問題?

public class AaaTest {
    public static void main(String[] args) throws InterruptedException {
        Object obj=new Object();
        Ttt ttt=new Ttt(obj);
        ttt.start();
        synchronized(obj){
            obj.wait();
        }
        System.out.println("wait先執(zhí)行,程序通過");
    }
    static class Ttt extends Thread{
        Object obj;
        Ttt(Object obj){
            this.obj=obj;
        }
        public void run() {
            synchronized(obj){
                    obj.notify();
            }
        }
    }
}

這樣是否能夠100%保證 obj.wait(); 在 obj.notify(); 之前執(zhí)行?

回答
編輯回答
歆久

不能,主線程還是ttt線程,那個先進(jìn)入同步塊synchronized(obj){}無法保證,樓上正解

2017年7月1日 05:13
編輯回答
骨殘心

當(dāng)然不能!
因為哪個線程先進(jìn)入同步塊是不確定的。

main方法可以這樣改:

synchronized(obj) {
    ttt.start();
    obj.wait();
}

這樣可以保證ttt線程即使先于obj.wait()方法執(zhí)行,也無法進(jìn)入同步塊。

2018年8月25日 19:22