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() {// 每條線程執行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(); } // 運行結果是只set了30次}
我的疑惑是notify()發布通知,為什么不會讓其他線程的wait()方法繼續執行下去呢?
問題解答
回答1:當你隊列的數量大于10的時候, 你每個線程都是先wait()住了, 不會走到notify()的啊. 你需要一個單獨的線程去監控隊列的大小, 大于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(); } }}
然后有個監控線程
class Monitor implements Runnable { private MyObject myObj; public Monitor(MyObject myObj) { this.myObj = myObj; } @Override public void run() { while (true) {myObj.delta(); } }}
相關文章:
1. docker start -a dockername 老是卡住,什么情況?2. python中merge后文件莫名變得非常大3. css3 - [CSS] 動畫效果 3D翻轉bug4. 希望講講異常處理5. javascript - 關于<a>元素與<input>元素的JS事件運行問題6. java - 為什么第一個線程已經釋放了鎖,第二個線程卻不行?7. css3 - 純css實現點擊特效8. mysql - 記得以前在哪里看過一個估算時間的網站9. javascript - 如何將一個div始終固定在某個位置;無論屏幕和分辨率怎么變化;div位置始終不變10. 大家好,我想請問一下怎么做搜索欄能夠搜索到自己網站的內容。
