java - 對于notify()/wait()的一點疑惑
問題描述
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(); } // 運行結(jié)果是只set了30次}
我的疑惑是notify()發(fā)布通知,為什么不會讓其他線程的wait()方法繼續(xù)執(zhí)行下去呢?
問題解答
回答1:當(dāng)你隊列的數(shù)量大于10的時候, 你每個線程都是先wait()住了, 不會走到notify()的啊. 你需要一個單獨的線程去監(jiān)控隊列的大小, 大于10的時候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(); } }}
然后有個監(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. php - 第三方支付平臺在很短時間內(nèi)多次異步通知,訂單多次確認收款2. css3 - css before 中文亂碼?3. javascript - 百度echarts series數(shù)據(jù)更新問題4. css - 求推薦幾款好用的移動端頁面布局調(diào)試工具呢?5. mysql - 一個表和多個表是多對多的關(guān)系,該怎么設(shè)計6. python - type函數(shù)問題7. mysql新建字段時 timestamp NOT NULL DEFAULT ’0000-00-00 00:00:00’ 報錯8. css3 - 手機網(wǎng)頁中用css寫1px的描邊,為什么需要加一句overflow:hidden才能真正顯示1px?9. javascript - node服務(wù)端渲染的困惑10. Mysql && Redis 并發(fā)問題
