java - Condition 接口(interface)中的 signalAll 与对象中的 notifyAll

标签 java multithreading concurrency

1) 昨天我才问这个问题Condition vs wait notify mechanism

2) 我想编辑相同的内容并在我的问题中添加一些 ifs,但因为它可能会变得很麻烦并且包含足够多的文本来让读者不感兴趣和感到困惑,所以我想在这里问一个新问题。

3) 在我的帖子的上下文中,其 url 在第 1 点中给出),考虑 4 个线程的情况,P1,T1 和 P2,T2 作用于单个数据结构“S”。

4) 我试图再次说明使用 Condition 接口(interface)相对于等待通知的优势。

5) 考虑代码

final Lock lock = new ReentrantLock();
Condition c1 = lock.newCondition();
Condition c2 = lock.newCondition();
Condition c3 = lock.newCondition();
Condition c4 = lock.newCondition();

6) 考虑 P1,T1 使用 c1,c2(以标准的 await()/signalAll() 方式)。考虑 P2、T2 使用 c3、c4(以标准的 await()/signalAll() 方式),让我们分别说 put、take、put1、take1 方法。

7) 当我执行 c1.signalAll() 时,只有等待/因为条件 1 的线程 会收到信号。我说的有道理吗?

8) 考虑一个等待/通知机制来实现同样的说法,

private static final Object lock= new Object();
synchronized(lock)

考虑 put、take、put1、take1,因此如果任何线程在任何一个条件满足时执行 lock.notifyAll(),即使是因为其他条件而等待/等待的线程也会收到通知。真的吗 ?。这是我们可以算作在条件机制上使用等待/通知的缺点吗?

最佳答案

是的,你是对的。 Condition 类是内在条件队列的泛化(通过 Object.waitObject.notifyObject 控制的队列) .notifyAll).

我将引用 Brian Goetz 的 Java Concurrency in Practice [p.306-307]

Intrinsic condition queues have several drawbacks. Each intrinsic lock can have only one associated condition queue, which means that in classes like BoundedBuffer multiple threads might wait on the same condition queue for different condition predicates, and the most common pattern for locking involves exposing the condition queue object. Both of these factors make it impossible to enforce the uniform waiter requirement for using notifyAll. If you want to write a concurrent object with multiple condition predicates, or you want to exercise more control over the visibility of the condition queue, the explicit Lock and Condition classes offer a more flexible alternative to intrinsic locks and condition queues.

A Condition is associated with a single Lock, just as a condition queue is associated with a single intrinsic lock; [...] And just as Lock offers a richer feature set than intrinsic locking, Condition offers a richer feature set than intrinsic condition queues: multiple wait sets per lock, interruptible and uninterruptible condition waits, deadline-based waiting, and a choice of fair or nonfair queueing.

关于java - Condition 接口(interface)中的 signalAll 与对象中的 notifyAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10407708/

相关文章:

javafx - 为什么 ExecutorService 不返回我的任务结果?

c++ - 在 windows 中使用互斥量进行进程间同步(win32 或 C++)

concurrency - 我们可以不以同步方式运行池中的每个任务吗?

java - 点击“设置”时动态壁纸崩溃

java - BlueJ 中的编译错误- if else with return 语句

计算 Pi 多线程 pthread

Java 进程 exitValue 错误

go - golang游览网络爬虫练习的简单解决方案

java - 替换 Spring PayloadValidatingInterceptor 中的 XML MessageFormatter

java - 从嵌套 HashMap 中检索值