java - 對于notify()/wait()的一點(diǎn)疑惑
問題描述
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(); } // 運(yùn)行結(jié)果是只set了30次}
我的疑惑是notify()發(fā)布通知,為什么不會讓其他線程的wait()方法繼續(xù)執(zhí)行下去呢?
問題解答
回答1:當(dāng)你隊(duì)列的數(shù)量大于10的時候, 你每個線程都是先wait()住了, 不會走到notify()的啊. 你需要一個單獨(dú)的線程去監(jiān)控隊(duì)列的大小, 大于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. javascript - react input file2. python - beautifulsoup獲取網(wǎng)頁內(nèi)容的問題3. python - 能通過CAN控制一部普通的家用轎車嗎?4. html5 - 只用CSS如何實(shí)現(xiàn)input框的寬度隨框里輸入的內(nèi)容長短自動適應(yīng)?5. javascript - angularjs ngblur不生效 onblur生效,為什么?6. 人工智能 - python 機(jī)器學(xué)習(xí) 醫(yī)療數(shù)據(jù) 怎么學(xué)7. centos7 編譯安裝 Python 3.5.1 失敗8. mysql - 分庫分表、分區(qū)、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處9. javascript - 關(guān)于css絕對定位在ios瀏覽器被橡皮筋遮擋的問題10. c++ - 請問MySQL_Connection::isReadOnly 怎么解決?
