java - 对象与条件,wait() 与 await()

标签 java multithreading concurrency parallel-processing reentrantlock

在一个关于锁的编程练习的解决方案中,我注意到他们使用一个对象来同步,所以像这样:

Lock lock = new ReentrantLock();
Object obj = new Object();

在一个方法中:

synchronized(obj){
obj.wait();}

我的问题是,我可以改用条件吗,比方说:

Condition cond = lock.newCondition();

然后在方法中使用,

cond.await()

而不是将其放入同步块(synchronized block)中?

编辑:解决方案: enter image description here

我将如何使用条件实现它?

最佳答案

是的。但是你必须先获得锁。请参阅 Condition.await() 的文档:

The current thread is assumed to hold the lock associated with this Condition when this method is called. It is up to the implementation to determine if this is the case and if not, how to respond. Typically, an exception will be thrown (such as IllegalMonitorStateException) and the implementation must document that fact.

synchronized (obj) {
    while (<condition does not hold>)
        obj.wait();
    ... // Perform action appropriate to condition
}

类似于

ReentrantLock lock = new ReentrantLock();
Condition cond = lock.newCondition();
lock.lock();
try {
    while (<condition does not hold>)
        cond.await();
    }       
} finally {
    lock.unlock();
}

关于java - 对象与条件,wait() 与 await(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51063963/

相关文章:

java - 我如何知道上下文是 Activity 还是 IntentService?

grails - 如果超时,是否有任何方法可以获取 PromiseList 的结果

c++ - 使用lambda表达式创建线程时,如何为每个线程提供自己的lambda表达式拷贝?

c - 使用 posix C 同时多次轮询信号量

c# - 并行执行使用异步的循环

java - websphere 应用程序服务器处理多少个并发请求(WAS 8.0)?

javascript - 使用 Nashorn 将 Javascript 函数作为功能接口(interface)类型传递给 Java 方法

java - AchartEngine 获取触摸点位置

java - onClick MediaPlayer 错误所有音频均已播放

multithreading - 跨线程编码 COM 接口(interface)的首选方法是什么?