java - 關(guān)于多線程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之后 要等到這個代碼塊結(jié)束之后才會把鎖讓出去,當(dāng)然如果在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() 應(yīng)該會阻塞主線程,并沒有其他地方notify而去掉t1.start()之后,就能阻塞住了
這是什么道理?編譯器優(yōu)化?還是synchronized代碼塊內(nèi)如果不對monitor進(jìn)行操作,結(jié)束主動notify??
問題解答
回答1:并不是優(yōu)化其實,跟線程的執(zhí)行有關(guān)的。在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.
看到加黑體,其實是線程結(jié)束之后調(diào)用的notifyAll導(dǎo)致wait蘇醒的。并不是什么虛擬機(jī)優(yōu)化導(dǎo)致的。希望能解答你的困惑
相關(guān)文章:
1. 如何解決docker宿主機(jī)無法訪問容器中的服務(wù)?2. angular.js - 輸入郵箱地址之后, 如何使其自動在末尾添加分號?3. javascript - 如何使用nodejs 將.html 文件轉(zhuǎn)化成canvas4. javascript - html5的data屬性怎么指定一個function函數(shù)呢?5. docker-compose中volumes的問題6. 在mac下出現(xiàn)了兩個docker環(huán)境7. python - Scrapy存在內(nèi)存泄漏的問題。8. javascript - 后臺管理系統(tǒng)左側(cè)折疊導(dǎo)航欄數(shù)據(jù)較多,怎么樣直接通過搜索去定位到具體某一個菜單項位置,并展開當(dāng)前菜單9. angular.js - $stateChangeSuccess事件在狀態(tài)跳轉(zhuǎn)的時候不執(zhí)行?10. java如何生成token?
