我正在进行LinkedBlockingQueue的内部实现 put(E e)和take()功能。
public E take() throws InterruptedException {
E x;
int c = -1;
final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock;
takeLock.lockInterruptibly();
try {
while (count.get() == 0) {
notEmpty.await();
}
x = dequeue();
c = count.getAndDecrement();
if (c > 1)
**notEmpty.signal();**
} finally {
takeLock.unlock();
}
if (c == capacity)
signalNotFull();
return x;
}
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
// Note: convention in all put/take/etc is to preset local var
// holding count negative to indicate failure unless set.
int c = -1;
Node<E> node = new Node<E>(e);
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
putLock.lockInterruptibly();
try {
/*
* Note that count is used in wait guard even though it is
* not protected by lock. This works because count can
* only decrease at this point (all other puts are shut
* out by lock), and we (or some other waiting put) are
* signalled if it ever changes from capacity. Similarly
* for all other uses of count in other wait guards.
*/
while (count.get() == capacity) {
notFull.await();
}
enqueue(node);
c = count.getAndIncrement();
if (c + 1 < capacity)
**notFull.signal();**
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
}
在这两种方法中,在与容量进行比较后调用条件时,没有得到signal()的原因。 如果任何人能够解释它,那将是非常值得赞赏的。
答案 0 :(得分:2)
以下是我可以考虑使用的一种情况:
if (c > 1)
notEmpty.signal();
假设队列为空,并且有3个线程,thread_1,thread_2,thread_3。
take()
,在notEmpty.await()
被阻止。take()
,在notEmpty.await()
被阻止。take()
,在notEmpty.await()
被阻止。然后,还有其他3个线程,thread_4,thread_5,thread_6。
put()
,在队列中添加一个元素,signal
thread_1。takeLock
,然后尝试获取第一个元素。put()
,在队列中添加另一个元素,并signal
thread_2。takeLock
,但thread_1现在正在持有锁,所以它必须等待。InterruptedException
并终止。c > 1
。如果thread_1没有调用signal
,则thread_3无法唤醒并获取第二个元素。 signal
,thread_3唤醒,并获取第二个元素。