久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

java - 關(guān)于多線程notify的問(wèn)題

瀏覽:107日期:2023-12-10 15:47:24

問(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)致的。希望能解答你的困惑

標(biāo)簽: java
相關(guān)文章:
主站蜘蛛池模板: 中牟县| 南漳县| 宜宾县| 江孜县| 湄潭县| 绵竹市| 莫力| 梨树县| 西乌| 永善县| 新竹市| 岳普湖县| 广元市| 桦川县| 辰溪县| 左权县| 扎鲁特旗| 西林县| 民丰县| 讷河市| 随州市| 阿拉尔市| 哈尔滨市| 遂平县| 南川市| 平利县| 景泰县| 丹东市| 沈丘县| 西华县| 巢湖市| 双鸭山市| 稷山县| 阿拉尔市| 犍为县| 龙游县| 密云县| 城固县| 湖北省| 湘西| 富宁县|