在重入锁中等待条件
2022-09-01 10:55:47
以下代码取自条件
的 JavaDoc:
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 个线程,使用者和生产者,一个使用 ,一个在 的单个实例上。take
put
BoundedBuffer
假设 Consumer 先去,在其中他锁定并循环运行。take()
lock
notEmpty.await();
现在生产者怎么可能进入锁定的方法,这已经被消费者持有了?put()
lock
我在这里错过了什么?线程是否在等待其条件之一时“暂时释放”?锁的重入究竟意味着什么?lock