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è)方法的注釋上面寫(xiě)著一句話
<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. 點(diǎn)擊頁(yè)面就自動(dòng)輸入到mysql.求解2. java - IDEA從SVN檢出項(xiàng)目 并在tomcat上運(yùn)行 求詳細(xì)流程3. node.js - 帶有node_modules目錄的項(xiàng)目,用phpstorm打開(kāi)速度極慢,怎么解決?4. node.js - nodejs使用formidable上傳文件問(wèn)題5. java - 多叉樹(shù)求值,程序高手,算法高手看過(guò)來(lái)6. javascript - windos下第一次用Django無(wú)法正確創(chuàng)建工程目錄7. css - 請(qǐng)問(wèn)B站頂部的模糊半透明導(dǎo)航條是怎么實(shí)現(xiàn)的呢?8. html5 - 有人做過(guò)防微信app界面的H5 demo嗎?9. javascript - JS用ajax爬取百度外賣店家信息10. 靜態(tài)資源文件引入無(wú)效
