并发阻塞队列ArrayBlockingQueue

ArrayBlockingQueue

一个由数组支持的有界阻塞队列。此队列按 FIFO(先进先出)原则对元素进行排序。队列的头部 是在队列中存在时间最长的元素。队列的尾部 是在队列中存在时间最短的元素。新元素插入到队列的尾部,队列获取操作则是从队列头部开始获得元素。

这是一个典型的“有界缓存区”,固定大小的数组在其中保持生产者插入的元素和使用者提取的元素。一旦创建了这样的缓存区,就不能再增加其容量。试图向已满队列中放入元素会导致操作受阻塞;试图从空队列中提取元素将导致类似阻塞。

此类支持对等待的生产者线程和使用者线程进行排序的可选公平策略。默认情况下,不保证是这种排序。然而,通过将公平性 (fairness) 设置为 true 而构造的队列允许按照 FIFO 顺序访问线程。公平性通常会降低吞吐量,但也减少了可变性和避免了“不平衡性”。

1. 内部属性

/** The queued items */
    //内部元素
    final Object[] items;

    /** items index for next take, poll, peek or remove */
    //take操作的位置,该位置从0到length-1,再到0
    int takeIndex;

    /** items index for next put, offer, or add */
    //put操作的位置,该位置从0到length-1,再到0;putIndex始终指向下一个元素将要插入的位置
    int putIndex;

    /** Number of elements in the queue */
    //队列中的元素总数
    int count;

    /*
     * Concurrency control uses the classic two-condition algorithm
     * found in any textbook.
     */

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

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

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

如上所示,数据结构是数组,通过ReentrantLock来进行同步,两个Condition分别对写和读进行阻塞

2. 常用方法

add

    public boolean add(E e) {
        if (offer(e))
            return true;
        else
            throw new IllegalStateException("Queue full");
    }

add操作用于添加元素,内部调用offer,添加不成功时抛出异常.那看看offer是怎么实现的

offer

    public boolean offer(E e) {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            //如果队列已满返回false
            if (count == items.length)
                return false;
            else {
                //否则入队
                enqueue(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }
    
    public boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException {

        checkNotNull(e);
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            //超时时间内还没插入成功则返回
            while (count == items.length) {
                if (nanos <= 0)
                    return false;
                nanos = notFull.awaitNanos(nanos);
            }
            enqueue(e);
            return true;
        } finally {
            lock.unlock();
        }
    }
    
    private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        //入队
        items[putIndex] = x;
        //移动putIndex,如果putIndex已经指向队尾则将putIndex重新指向队首
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        //有元素入队,则唤醒被阻塞的读线程
        notEmpty.signal();
    }

offer方法使用lock进行同步,判读队列是否已满,未满则入队,同时唤醒被阻塞的读线程,否则直接或者等待超时后返回false。

put

    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();
        }
    }

put操作和offer又很类似,只不过队列已满的时候不返回,而是一直阻塞等待队列有空余位置。
接下来看看读操作

poll

    public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            //没有元素直接返回或者出队
            return (count == 0) ? null : dequeue();
        } finally {
            lock.unlock();
        }
    }
    
    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            //没有元素时等待超时
            while (count == 0) {
                if (nanos <= 0)
                    return null;
                nanos = notEmpty.awaitNanos(nanos);
            }
            return dequeue();
        } finally {
            lock.unlock();
        }
    }
    
    private E dequeue() {
        // assert lock.getHoldCount() == 1;
        // assert items[takeIndex] != null;
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        //取出当前元素并将队列该空间置为null
        E x = (E) items[takeIndex];
        items[takeIndex] = null;
        //移动takeIndex,当takeIndex超过队尾,则重新移动到队首
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        //移除元素后有剩余空间,则唤醒被写操作阻塞的线程
        notFull.signal();
        return x;
    }
    

poll操作与offer操作相反,实现思路基本相同

take

    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            //无限期等待队列不为空
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

take与put操作都是无限期阻塞当前线程直到队列不为空或者队列未满。

peek

    public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return itemAt(takeIndex); // null when queue is empty
        } finally {
            lock.unlock();
        }
    }

peek peek只返回而不删除元素。

总结

1、ArrayBlockingQueue内部数据结构是数组
2、使用ReentrantLock进行同步
3、使用notEmpty和notFull条件阻塞和唤醒相关的操作
4、使用一把锁,上面的这些方法同一时刻只能有一个线程执行,意味着读和写不能同时进行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值