第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

關(guān)于Java中 Object.notify()方法的疑問

關(guān)于Java中 Object.notify()方法的疑問

眼眸繁星 2019-02-18 18:23:32
package com.chong; public class Main { public static void main(String args[]){ Object obj=new Object(); Thread t1=new Thread(new Runnable() { @Override public void run() { synchronized (obj) { try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("t1 end"); } } }); Thread t2=new Thread(new Runnable() { @Override public void run() { synchronized (obj) { obj.notify(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("t2 end"); } } }); t1.start(); t2.start(); } } 如上代碼,結(jié)果是:t2先執(zhí)行完,t1后執(zhí)行完。 查資料,notify()方法是通知一個(gè)等待在該對(duì)象上的線程,不會(huì)釋放鎖。 那么,obj.notify()方法,寫在同步代碼塊里的最開始或者最末尾處,jvm內(nèi)部處理邏輯上有什么差異嗎?平時(shí)寫代碼,在這里有什么需要注意的點(diǎn)嗎?
查看完整描述

4 回答

?
躍然一笑

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個(gè)贊

你這么寫只是個(gè)演示代碼,wait()和notify()是配合生產(chǎn)者-消費(fèi)者模型使用的。Android中的Volley框架也是使用這種原理來進(jìn)行多線程的并發(fā)調(diào)度。
不需要考慮JVM,你只需要考慮釋放時(shí)機(jī)和通知時(shí)間,建議參考我的這篇博客:Java并發(fā)寫作——wait-notify機(jī)制

查看完整回答
反對(duì) 回復(fù) 2019-03-01
?
一只甜甜圈

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊

引用jdk6中wait方法的注釋

The current thread must own this object's monitor. The thread
releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.

對(duì)應(yīng)到題主的代碼wait調(diào)用后會(huì)釋放obj對(duì)象的鎖。
另外,sleepyield方法是不會(huì)釋放對(duì)象鎖的。

查看完整回答
反對(duì) 回復(fù) 2019-03-01
?
交互式愛情

TA貢獻(xiàn)1712條經(jīng)驗(yàn) 獲得超3個(gè)贊

沒問題,這個(gè)答案。如果沒有wait,那么notify有毛用

查看完整回答
反對(duì) 回復(fù) 2019-03-01
?
牛魔王的故事

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超3個(gè)贊

你這代碼應(yīng)該會(huì)出現(xiàn)t2執(zhí)行完,t1不會(huì)執(zhí)行完的情況,這叫過早的notify,你應(yīng)該確保線程1總是先于2執(zhí)行才行。

查看完整回答
反對(duì) 回復(fù) 2019-03-01
  • 4 回答
  • 0 關(guān)注
  • 804 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)