java - nofity的顺序All在生产者-消费者模式中

标签 java parallel-processing

我有一个生产者-消费者模式的示例,其中 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/

相关文章:

java - 使用 Netty 或其他轻量级 NIO 库的请求-响应

python-3.x - Python : Running nested loop, 2D 移动窗口,并行

c++ - 低效的内存访问模式和不规则的跨步访问

使用 PyCUDA 进行 Python 多处理

parallel-processing - Julia 中的进程数

java - 如何在 mybatis XML 映射器中使用 partials 或 helpers?

java - 如何从 Eclipse 在我的 Activity Android 设备中运行我开发的 Android 应用程序?

java - Spring boot META-INF/build-info.properties 不在工件中

Java lwgjl2 更改光标图像

c# - 如何将 Parallel.ForEach 与线程局部状态一起使用?