03-阻塞队列实现原理

大雄只看了ArrayBlockingQueue, 感觉应该是差不多的。如有错误,欢迎指出。

一句话可以说明白,ArrayBlockingQueue是基于ReentrantLock及其Condition实现的。说到这里,你可能已经知道怎么搞了。

看一下这个构造

public ArrayBlockingQueue(int capacity, boolean fair) {
    if (capacity <= 0)
        throw new IllegalArgumentException();
    this.items = new Object[capacity];
    lock = new ReentrantLock(fair);
    notEmpty = lock.newCondition(); // 划重点
    notFull =  lock.newCondition(); // 划重点
}

似曾相识的感觉,我们在第二章第5节实现的BoundList就是这么搞的

看看put

public void put(E e) throws InterruptedException {
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        // 这个while是必要的
        while (count == items.length)
            // 满了就放到notFull的等待队列
            notFull.await();
        enqueue(e);
    } finally {
        lock.unlock();
    }
}

private void enqueue(E x) {
    final Object[] items = this.items;
    items[putIndex] = x;
    // 这是个循环数组
    if (++putIndex == items.length)
        putIndex = 0;
    count++;
    // 通知等待的消费者,有元素可以消费了
    notEmpty.signal();
}

看看take

DelayQueue

DelayQueue是有他的特殊之处的,所以看一看

看他的入队

再看出队

SynchronousQueue

这个初看了下,没太明白,后续再看看吧

TODO: 待补充

最后更新于

这有帮助吗?