来自Java Condition Docs
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
进入临界区,现在需要从不同的线程获取它。
如果你仔细观察Condition.await()的Javadoc,你会看到await()方法以原子方式释放锁并暂停自身:
“与此条件相关联的锁被原子释放,并且当前线程因线程调度而被禁用,并处于休眠状态,直到发生四件事之一......”