JUC源码阅读-ArrayBlockingQueue

ArrayBlockingQueue,是一个由数组实现的有界阻塞队列。该队列采用FIFO的原则对元素进行排序添加的。

ArrayBlockingQueue为有界且固定,其大小在构造时由构造函数来决定,确认之后就不能再改变了。ArrayBlockingQueue支持对等待的生产者线程和使用者线程进行排序的可选公平策略,但是在默认情况下不保证线程公平的访问,在构造时可以选择公平策略(fair = true)。公平性通常会降低吞吐量,但是减少了可变性和避免了“不平衡性”。

成员变量

//存储的对象,是一个定长数组
    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;

ArrayBlockingQueue内部使用重入锁ReentrantLock和Condition实现多线程的并发操作的。ArrayBlocingQueue的成员变量如源码所示

  1. items,定长数组,用于存储元素
  2. taskIndex,队首位置
  3. putIndex,队尾位置
  4. count,元素个数
  5. lock,锁,出列和入列都使用该所
  6. notEmpty,出列条件
  7. notFull,入列条件

构造方法

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

构造方法传入了队列的大小值,以及使用公平锁方式还是非公平锁方式的实现。

入列方法

入列方法有以下几种

  1. add(E e) :将指定的元素插入到此队列的尾部(如果立即可行且不会超过该队列的容量),在成功时返回 true,如果此队列已满,则抛出 IllegalStateException
  2. offer(E e) :将指定的元素插入到此队列的尾部(如果立即可行且不会超过该队列的容量),在成功时返回 true,如果此队列已满,则返回 false
  3. offer(E e, long timeout, TimeUnit unit) :将指定的元素插入此队列的尾部,如果该队列已满,则在到达指定的等待时间之前等待可用的空间
  4. put(E e) :将指定的元素插入此队列的尾部,如果该队列已满,则等待可用的空间

这些方法都使用了重入锁的加锁方式,可以阅读add方法查看源码

public boolean add(E e) {
        return super.add(e);
    }
public boolean add(E e) {
        //添加成共返回true
        if (offer(e))
            return true;
        else
            //添加失败抛出异常
            throw new IllegalStateException("Queue full");
    }
public boolean offer(E e) {
        checkNotNull(e);//判断对象为空
        final ReentrantLock lock = this.lock;
        lock.lock();//加锁
        try {
            if (count == items.length)
                return false;//队列已满,返回false
            else {
                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;
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        notEmpty.signal();
    }

add方法整体流程如下:

  1. 首先检查对象是否为null
  2. 不为null加锁
  3. 判断队列是否已满,已满返回false,抛出异常
  4. 没有满入栈,并通知阻塞在出列的线程;
  5. 解锁

出列

//出列
    public E poll() {
        final ReentrantLock lock = this.lock;
        //加锁
        lock.lock();
        try {
            //数量为null,返回空
            return (count == 0) ? null : dequeue();//出列
        } finally {
            lock.unlock();//解锁
        }
    }
private E dequeue() {
        // assert lock.getHoldCount() == 1;
        // assert items[takeIndex] != null;
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex];
        items[takeIndex] = null;
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();//维护迭代器
        notFull.signal();//通知阻塞在入列的线程
        return x;
    }

出列流程:首先进行加锁,判断队列数量是否为0,为0返回Null,不为0进行出列操作

dequeue方法执行出列操作,就是从takeIndex 位置处取出对象,同时如果迭代器不为null,维护迭代器,然后通知阻塞在入列的线程。

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值