【发布时间】:2011-03-30 05:07:07
【问题描述】:
看了JDKLinkedBlockingQueue类,迷路了。
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;
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(e);
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
}
请看最后一个条件(c == 0),我想应该是(c != 0)
谢谢,我明白了。 但是我还有一个关于 LinkedBlockingQueue 实现的问题。 enqueue 和 dequeue 函数不能相交。我看到当 put() 被执行时, take() 也可以被执行。而且头尾对象没有同步,入队和出队可以在不同的线程中同时工作。它不是线程安全的,可能会发生故障。
【问题讨论】:
-
至于编辑:你可能在拍摄中错过了
while (count.get() == 0) notEmpty.await(); -
如果您有新问题,请提出一个新问题 -- 现有问题刚刚被更改,这真的很令人困惑。
标签: java collections