来自 Java条件文档
class BoundedBuffer<E> {
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(E 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 E take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await();
E x = (E) items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}
假设一个线程Produce调用put,所以Produce现在拥有锁lock。但while条件为真也是Produce如此notFull.await()。我现在的问题是,如果一个线程Consume调用take, 在lock.lock()说明到底发生了什么的那一行?
我有点困惑,因为我们让旧lock的进入关键部分,现在需要从不同的线程获取它。