ArrayBlockingQueue

本文深入探讨了阻塞队列的工作原理及其实现细节,详细解释了如何利用ReentrantLock和Condition实现线程间的同步控制,确保在队列满或空时线程能够正确等待。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

阻塞队列
当线程往队列里放,队列已满,等待队列不满条件(notFull)满足后线程才能继续
当线程往队列里取,队列已空,等待队列不空条件(notEmpty)满足后线程才能继续

/** 队列不空条件 */
    private final Condition notEmpty;
/** 队列不满条件 */
    private final Condition notFull;
 public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        //ArrayBlockingQueue中lock的2个condition
        notEmpty = lock.newCondition();
        notFull =  lock.newCondition();
    }
 public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                //如果count达到了数组的长度,即队列已满,则队列不满条件等待
                //多个线程在这里休眠等待队列不满条件条件满足后唤醒,唤醒队列
                //会重新竞争锁
                notFull.await();
           //获得锁的继续插入    
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }
private void enqueue(E x) {
        final Object[] items = this.items;
        items[putIndex] = x;
        //有界队列,到putIndex到数组头了,就返回来
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        notEmpty.signal();
    }
public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
               //如果count为0,即队列已空,则队列不空条件等待
                //多个线程在这里休眠等待队列不空条件满足后唤醒
                //会重新竞争锁
                notEmpty.await();
             //获得锁的继续取       
            return dequeue();
        } finally {
            lock.unlock();
        }
    }
 private E dequeue() {
        final Object[] items = this.items;

        E x = (E) items[takeIndex];
        items[takeIndex] = null;
        //takeIndex到头了,返回0
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        notFull.signal();
        return x;
    }

源码比较简单,也是一个对lock和condition的知识点的加深理解。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值