在一个关于锁的编程练习的解决方案中,我注意到他们使用一个对象来同步,所以像这样:
Lock lock = new ReentrantLock();
Object obj = new Object();
在一个方法中:
synchronized(obj){
obj.wait();}
我的问题是,我可以改用条件吗,比方说:
Condition cond = lock.newCondition();
然后在方法中使用,
cond.await()
而不是将其放入同步块(synchronized block)中?
我将如何使用条件实现它?
最佳答案
是的。但是你必须先获得锁。请参阅 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/