Java LinkedBlockingQueue 实现

标签 java collections

我看着 JDK LinkedBlockingQueue 类,迷路了。

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 实现的问题。 入队和出队功能不得相交。我看到当 put() 被执行时, take() 也可以被执行。 head 和 tail 对象没有同步,入队和出队可以在不同的线程中同时工作。它不是线程安全的,可能会发生故障。

最佳答案

不,目的是当队列从 0 变为 1 时(即第一次向空队列中添加内容)发出信号。将项目添加到已经有项目的队列时,您不需要“发出非空信号”。 (您会注意到 notEmpty 条件仅在队列计数 == 0 时才会等待)。

关于Java LinkedBlockingQueue 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5478284/

相关文章:

Java HashMap 检测冲突

java - achartengine 图形在relativelayout 中无法正确绘制

java - 允许特定用户访问 Spring Security

java - 为什么结果没有进入 Spring Data 应用程序

c++ - 如何正确编写模板模板参数?

c# - 优化字典键的内存要求

java - Java泛型映射键值键入

java - 单击按钮时 Spring 安全性检查用户是否已登录

java - Android 中的国家/地区代码选择器无法获取国家/地区代码

java - java.util.List 中的第一个元素被覆盖