条件变量的await()释放锁吗?
譬如下面的两个条件变量 isEmpty和isFull
当调用他们的await()时,lock.lock()上的锁会被释放吗?
这里有3个对象,一个i哦是lock,一个是isEmpty,一个是isFull
上锁的对象是lock,而不是isEmpty或者isFull
那isFull或者isEmpty释放的锁确实lock上的?
private volatile boolean usedData = true;//mutex for data
private final Lock lock = new ReentrantLock();
private final Condition isEmpty = lock.newCondition();
private final Condition isFull = lock.newCondition();
public void setData(int data) throws InterruptedException {
lock.lock();
try {
while(!usedData) {//wait for data to be used
isEmpty.await();
}
this.data = data;
isFull.signal();//broadcast that the data is now full.
usedData = false;//tell others I created new data.
}finally {
lock.unlock();//interrupt or not, release lock
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
await的doc有这么一句啊The lock associated with this Condition is atomically released
谢邀,
答案:
This method causes the current thread (call it <var>T</var>) to
place itself in the wait set for this object and then to relinquish
any and all synchronization claims on this object.
加入等待队列,并且放弃锁.