ArrayBlockingQueue 概览

底层使用数组实现.

常量代码:

 /** The queued items */
    final Object[] items;

    /** items index for next take, poll, peek or remove */
    int takeIndex;

    /** items index for next put, offer, or add */
    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;

    /**
     * Shared state for currently active iterators, or null if there
     * are known not to be any.  Allows queue operations to update
     * iterator state.
     */
    transient Itrs itrs = null;

 

类图:

 

 

构造方法: 需要指定容量大小, 不会扩容. 默认锁是非公平调度.

/**
     * Creates an {@code ArrayBlockingQueue} with the given (fixed)
     * capacity and default access policy.
     *
     * @param capacity the capacity of this queue
     * @throws IllegalArgumentException if {@code capacity < 1}
     */
    public ArrayBlockingQueue(int capacity) {
        this(capacity, false);
    }

    /**
     * Creates an {@code ArrayBlockingQueue} with the given (fixed)
     * capacity and the specified access policy.
     *
     * @param capacity the capacity of this queue
     * @param fair if {@code true} then queue accesses for threads blocked
     *        on insertion or removal, are processed in FIFO order;
     *        if {@code false} the access order is unspecified.
     * @throws IllegalArgumentException if {@code capacity < 1}
     */
    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();
    }

    /**
     * Creates an {@code ArrayBlockingQueue} with the given (fixed)
     * capacity, the specified access policy and initially containing the
     * elements of the given collection,
     * added in traversal order of the collection's iterator.
     *
     * @param capacity the capacity of this queue
     * @param fair if {@code true} then queue accesses for threads blocked
     *        on insertion or removal, are processed in FIFO order;
     *        if {@code false} the access order is unspecified.
     * @param c the collection of elements to initially contain
     * @throws IllegalArgumentException if {@code capacity} is less than
     *         {@code c.size()}, or less than 1.
     * @throws NullPointerException if the specified collection or any
     *         of its elements are null
     */
    public ArrayBlockingQueue(int capacity, boolean fair,
                              Collection<? extends E> c) {
        this(capacity, fair);

        final ReentrantLock lock = this.lock;
        lock.lock(); // Lock only for visibility, not mutual exclusion
        try {
            int i = 0;
            try {
                for (E e : c) {
                    checkNotNull(e);
                    items[i++] = e;
                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                throw new IllegalArgumentException();
            }
            count = i;
            putIndex = (i == capacity) ? 0 : i;
        } finally {
            lock.unlock();
        }
    }

 

offer操作

向队列尾部插入一个元素, 如果队列有空闲空间则插入成功后返回 true,如果队列己 满则丢弃当前元素然后返回 false。如果 e元素为 null则抛出 NullPointerException异常 。另外, 该方法是不阻塞的 。  如果数据操作长度,则不再加入. 

 

put操作

向队列尾部插入一个元素,如果队列有空闲则插入后直接返回 true,如果队列己满则 阻塞当前线程直到队列有空闲井插入成功后返回 true,如果在阻塞时被其他线程设置了 中断标志, 则 被阻塞线程会抛出 InteηuptedException 异常而返回。另 外, 则抛出 NullPointerException 异常 。

 

take 操作

获取当前队列头部元素并从队列里面移除它。如果队列为空则阻塞当前线程直到队列 不为空然后返回元素,如果在阻塞时被其他线程设置了中断标志,则被阻塞线程会抛出 InterruptedException 异常而返回。

take 操作 的代码 也 比较简单,与 poll 相 比 只是代码( 2)不同。在这里,如果队列为 空则把当前线程挂起后放入 notEmpty 的条件 队列 , 等其他线程调用 notEmpty.signal() 方法 后再返回。需要注意的是,这里也是使用 while循环进行检测井等待而不是使用 if语句。

 

peek操作

获取队列头部元素但是不从队列里面移除它 ,如果队列为空则返回 null,该方法是不阻塞的.

ArrayBlockingQueue通过使用全局独占锁实现了同时只能有一个线 程进行入队或者出队操作,这个锁的粒度比较大,有点类似于在方法上添加 synchronized 的意思 。 其中 。offer 和 poll 操作通过简单的加锁进行入队、出队操作,而 put、 take 操 作则使用条件变量实现了,如果队列满则等待,如果队列空则等待,然后分别在出 队和入队操作中发送信号激活 等待线程实 现同步 。另外,相比 LinkedBlockingQueue, ArrayBlockingQueue的 size操作的结果是精确的, 因为计算前加了全局锁。

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值