【发布时间】:2019-02-11 08:46:45
【问题描述】:
来自 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 进入临界区,现在需要从不同的线程获取它。
【问题讨论】:
标签: java multithreading concurrency operating-system