ArrayBlockingQueue源码分析

ArrayBlockingQueue最核心的实现就是一把锁,两个条件。具体看源码如下:

/** Main lock guarding all access */
    final ReentrantLock lock;

    /** Condition for waiting takes */
    private final Condition notEmpty;

    /** Condition for waiting puts */
    private final Condition notFull;

put和take操作的时候都需要加锁,如果队列满了notFull.wait(),等待消费者消费掉信息后调用notFull.notify(),这样就可以继续put了。如果队列为空的原理也相似。 下面看下put和take的源码

public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            //如果当前数据到达最大值,生产者等待
            while (count == items.length)
                notFull.await();
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }
    
        public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            //如果当前数据为空,则消费者等待
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }
经验分享 程序员 微信小程序 职场和发展