以下代码取自 的JavaDocCondition
:
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();
}
}
}
想象一下 2 个线程,Consumer和Producer,一个使用take
,一个put
在BoundedBuffer
.
假设Consumer首先运行take()
,在其中他锁定了lock
并且现在循环运行notEmpty.await();
。
现在Producer怎么可能进入put()
锁定lock
已经由Consumer持有的方法?
我在这里想念什么?lock
线程等待其条件之一时是否“临时释放” ?锁的可重入性究竟意味着什么?