阅读Java 8文档关于java.util.concurrent.locks.Condition
接口的内容,给出以下示例:
class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final Object[] items = new Object[100];
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}
public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await();
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}
所以我的主要问题是:条件是如何工作的?
- 当它开始等待时,它会释放锁吗?(例如
notFull.await()
)? - 不同的线程可以获取相同的锁并移动,直到它
signal()
一个条件,唤醒其他线程吗? - 我认为这个例子会导致死锁,因为如果一个线程正在等待缓冲区不为空,并且它尚未释放锁,则另一个线程如何获取锁,清空缓冲区,
signal()
条件现在已满足,并通过如果等待缓冲区非空的线程尚未释放锁来释放锁?
这些都是初学者的问题。请帮帮我。
谢谢。