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