java - 對(duì)于notify()/wait()的一點(diǎn)疑惑
問(wèn)題描述
class MyObject{ private Queue<String> queue = new ConcurrentLinkedQueue<String>(); public synchronized void set(String s){ while(queue.size() >= 10){try { wait();} catch (InterruptedException e) { e.printStackTrace();} } queue.add(s); notify(); }}class Producer implements Runnable{ private MyObject myObj;public Producer(MyObject myObj) {this.myObj= myObj; } @Override public void run() {// 每條線程執(zhí)行30次setfor (int i = 0; i < 30; i++) { this.myObj.set('obj:' + i);} }}public static void main(String[] args){ Producer producer = new Producer(new MyObject()); // 生成30條線程 for (int i = 0; i < 10; i++) {Thread thread = new Thread(producer);thread.start(); } // 運(yùn)行結(jié)果是只set了30次}
我的疑惑是notify()發(fā)布通知,為什么不會(huì)讓其他線程的wait()方法繼續(xù)執(zhí)行下去呢?
問(wèn)題解答
回答1:當(dāng)你隊(duì)列的數(shù)量大于10的時(shí)候, 你每個(gè)線程都是先wait()住了, 不會(huì)走到notify()的啊. 你需要一個(gè)單獨(dú)的線程去監(jiān)控隊(duì)列的大小, 大于10的時(shí)候notify(), 比如可以把你的稍微改一下
class MyObject { private Queue<String> queue = new ConcurrentLinkedQueue<String>(); private volatile int limit = 10; public synchronized void set(String s) { if (queue.size() >= limit) {try { wait();} catch (InterruptedException e) { e.printStackTrace();} } queue.add(s); } public synchronized void delta() { if (queue.size() >= limit) {limit += 10;notify(); } }}
然后有個(gè)監(jiān)控線程
class Monitor implements Runnable { private MyObject myObj; public Monitor(MyObject myObj) { this.myObj = myObj; } @Override public void run() { while (true) {myObj.delta(); } }}
相關(guān)文章:
1. javascript - vue提示語(yǔ)法錯(cuò)誤,請(qǐng)問(wèn)錯(cuò)誤在哪?2. 淺談vue生命周期共有幾個(gè)階段?分別是什么?3. index.php錯(cuò)誤,求指點(diǎn)4. css - 關(guān)于偽類背景問(wèn)題5. javascript - 為什么我的animation-fill-mode 設(shè)置不生效6. html - JavaScript的Dom操作如何改變子元素的文本內(nèi)容7. css - 移動(dòng)端 oppo 手機(jī)之 Border-radius8. python - 抓包只抓到j(luò)son,真實(shí)的地址卻找不到9. java - web端百度網(wǎng)盤(pán)的一個(gè)操作為什么要分兩次請(qǐng)求服務(wù)器, 有什么好處嗎10. javascript - vue.js如何遞歸渲染組件.
