java - 關(guān)于多線程notify的問(wèn)題
問(wèn)題描述
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之后 要等到這個(gè)代碼塊結(jié)束之后才會(huì)把鎖讓出去,當(dāng)然如果在notify之后又有wait,那就會(huì)主動(dòng)把鎖讓出去 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();} }}
照理來(lái)說(shuō) t1.wait() 應(yīng)該會(huì)阻塞主線程,并沒(méi)有其他地方notify而去掉t1.start()之后,就能阻塞住了
這是什么道理?編譯器優(yōu)化?還是synchronized代碼塊內(nèi)如果不對(duì)monitor進(jìn)行操作,結(jié)束主動(dòng)notify??
問(wèn)題解答
回答1:并不是優(yōu)化其實(shí),跟線程的執(zhí)行有關(guān)的。在java doc中,public final synchronized void join(long millis)這個(gè)方法的注釋上面寫著一句話
<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.
看到加黑體,其實(shí)是線程結(jié)束之后調(diào)用的notifyAll導(dǎo)致wait蘇醒的。并不是什么虛擬機(jī)優(yōu)化導(dǎo)致的。希望能解答你的困惑
相關(guān)文章:
1. javascript - 關(guān)于定時(shí)器 與 防止連續(xù)點(diǎn)擊 問(wèn)題2. javascript - 求助關(guān)于js正則問(wèn)題3. objective-c - ios百度地圖定位問(wèn)題4. javascript - 求助這種功能有什么好點(diǎn)的插件?5. javascript - js 有什么優(yōu)雅的辦法實(shí)現(xiàn)在同時(shí)打開(kāi)的兩個(gè)標(biāo)簽頁(yè)間相互通信?6. 為何 localStorage、sessionStorage 屬于html5的范疇,但是為何 IE8卻支持?7. html5 - rudy編譯sass的時(shí)候有中文報(bào)錯(cuò)8. html - css 如何添加這種邊框?9. javascript - node.js服務(wù)端渲染解疑10. 微信開(kāi)放平臺(tái) - Android調(diào)用微信分享不顯示
