java中的notifyAll
在Java中的多生产者-消费者问题中,在循环内部使用notifyAll是否错误 下面是我正在谈论的代码片段java中的notifyAll,java,multithreading,producer-consumer,Java,Multithreading,Producer Consumer,在Java中的多生产者-消费者问题中,在循环内部使用notifyAll是否错误 下面是我正在谈论的代码片段 public void run() { while(producer_counter <= 64) { synchronized(list) { threadId1 = "Producer " + Thread.currentThread().getName(); //Bu
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();
}
}
}
}
您不应在while循环中使用list.notifyAll。将生成的项目添加到list.addproducer\计数器后,您可以使用notifyAll
// 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();
notifyAll是将同步对象状态的更改通知所有参与方。等待之后的第一个调用是多余的,因为没有发生状态更改。此调用不会使程序出错,但只会造成CPU周期的浪费:当缓冲区已满时,将调用notifyAll,所有其他线程在等待缓冲区的可用性时,转到processor only再次调用notifyAll,然后调用wait。因此,机器中的一个处理器总是忙于进行不必要的工作
顺便说一句,如果您不知道为什么会发生InterruptedException或任何其他异常以及如何处理它,那么您不应该捕获它。如果像这里一样,您不能编写公共void run throws InterruptedException,那么请编写
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
与RuntimeException不同,最好声明您自己的未检查异常。当您没有更改任何内容时,通知线程有什么意义?他们不需要知道什么,因为自从他们决定阻止以来没有任何变化。你应该解释为什么询问者不应该在循环中使用notifyAll。