![](/img/trans.png)
[英]Java wait and notifyAll: IllegalMonitorStateException
[英]notifyAll in java
在Java中的多個生產者-消費者問題中,在循環內使用notifyAll()
是錯誤的嗎?
這是我正在談論的代碼片段。
public void run() {
while(producer_counter <= 64) {
synchronized(list) {
threadId1 = "Producer " + Thread.currentThread().getName();
//Buffer size is 8
while(list.size() >= 8) {
System.out.println( "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(threadId1+ " found the buffer is full & waiting for a Consumer to consume.");
System.out.println( "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
try {
list.wait();
list.notifyAll();
}
catch (InterruptedException ie) {
ie.printStackTrace();
}
}
System.out.println(threadId1+ " produced item " + producer_counter);
//Adding the items produced to the list.
list.add(producer_counter);
producer_counter++;
//Invoking notify
list.notifyAll();
}
}
}
}
notifyAll()
用於通知所有有關同步對象狀態的更改。 因為沒有狀態更改,所以在wait()
之后的第一個調用是多余的。 該調用不會使程序出錯,只會浪費CPU周期:當緩沖區已滿時,將調用notifyAll()
,而所有其他線程在等待緩沖區可用時,僅進入處理器以再次調用notifyAll()
,然后調用wait()
。 結果,機器中的一個處理器將總是忙於進行不必要的工作。
順便說一句,如果您不知道它發生的原因以及如何處理,則不應捕獲InterruptedException
(或任何其他異常)。 如果像這里一樣無法編寫public void run() throws InterruptedException
,則編寫
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
最好聲明自己的未經檢查的異常,而不是RuntimeException
。
您不應該在while循環中使用list.notifyAll()。將產生的項目添加到列表list.add(producer_counter)后,您可以使用notify all。
// producer thread waits while list is full
while (list.size() >= 8){
list.wait();
}
// to insert the jobs in the list and plus 1 the counter
list.add(producer_counter);
producer_counter++;
// notifies the consumer threads that now it can start
//consuming
list.notifyAll();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.