java - 對於notify()/wait()的一點疑惑
PHP中文网
PHP中文网 2017-05-17 09:58:07
0
1
628
class MyObject{ private Queue queue = new ConcurrentLinkedQueue(); 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次set for (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()方法繼續執行下去呢?

PHP中文网
PHP中文网

认证高级PHP讲师

全部回覆 (1)
習慣沉默

當你隊列的數量大於10的時候, 你每個線程都是先wait()住了, 不会走到notify()的啊. 你需要一个单独的线程去监控队列的大小, 大于10的时候notify(), 例如可以把你的稍微改一下

class MyObject { private Queue queue = new ConcurrentLinkedQueue(); 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(); } } }
    最新下載
    更多>
    網站特效
    網站源碼
    網站素材
    前端模板
    關於我們 免責聲明 Sitemap
    PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!