我有一个生产者-消费者模式的示例,其中 notifyAll
放置在 queue.remove()
之前。这很重要还是只是为了方便?
synchronized void post(Work w) {
while (queue.isFull()) this.wait();
queue.add(w);
this.notifyAll();
}
synchronized Work get() {
while (queue.isEmpty()) this.wait();
// is the order at this point important, or could I switch this part?
this.notifyAll();
return queue.remove();
}
最佳答案
你可以调换它们并仍然得到相同的行为。这样做是因为否则您将需要一个额外的局部变量和一行代码来保存从队列中删除的元素。这并不重要(它不会影响性能),但为什么不以最简单的方式编写代码。
Work w = queue.remove(); // Unnecessary
this.notifyAll();
return w;
关于java - nofity的顺序All在生产者-消费者模式中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46693970/