在 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
。
关于java - java中的notifyAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49269772/