久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

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

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

瀏覽:148日期: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
相關文章:
主站蜘蛛池模板: 延安市| 运城市| 锡林郭勒盟| 武穴市| 旺苍县| 那曲县| 湘西| 乐陵市| 昭觉县| 霍林郭勒市| 河间市| 澎湖县| 枞阳县| 堆龙德庆县| 阳谷县| 习水县| SHOW| 商丘市| 湖南省| 山东省| 山丹县| 丹巴县| 潼关县| 利辛县| 湘西| 武冈市| 两当县| 莲花县| 长沙县| 任丘市| 灵武市| 高清| 瑞丽市| 仙游县| 大洼县| 邯郸县| 工布江达县| 周至县| 枣阳市| 舒城县| 根河市|