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

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

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

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

問題描述

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

標(biāo)簽: java
相關(guān)文章:
主站蜘蛛池模板: 大连市| 丰台区| 迭部县| 聂拉木县| 离岛区| 邛崃市| 钟祥市| 合水县| 东安县| 巩义市| 敖汉旗| 北辰区| 永仁县| 无为县| 桦南县| 绥阳县| 沾化县| 遵义市| 扎鲁特旗| 水富县| 唐海县| 马山县| 青海省| 英超| 福鼎市| 祁东县| 奉节县| 巴中市| 浦县| 阳春市| 从化市| 竹山县| 云梦县| 卓资县| 芮城县| 绥德县| 枣庄市| 嘉善县| 施甸县| 邳州市| 卢湾区|