您的位置:首頁技術文章
文章詳情頁

java - 對于notify()/wait()的一點疑惑

瀏覽:124日期:2023-12-17 16:29:46

問題描述

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(); } }}

標簽: java
相關文章:
国产综合久久一区二区三区