ArrayBlockingQueue原理分析

参考: https://www.jianshu.com/p/cc308d82cc71
1.构造方法
一共提供了三个构造方法,最核心的是第二个构造方法(如下);第三个构造方法多了数据初始化

/**
 * 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();// 初始化非空 Condition
    notFull =  lock.newCondition();// 初始化非满 Condition
}

2.Add 方法
以 add 方法作为入口,在 add 方法中会调用父类的 add 方法,也就是 AbstractQueue.
一般这种写法都是调用父类的模版方法来解决通用性问题.
add 方法最终还是调用 offer 方法来添加数据,返回一个添加成功或者失败的布尔值反馈

3.offer 方法

/**
 * Inserts the specified element at the tail of this queue if it is
 * possible to do so immediately without exceeding the queue's capacity,
 * returning {@code true} upon success and {@code false} if this queue
 * is full.  This method is generally preferable to method {@link #add},
 * which can fail to insert an element only by throwing an exception.
 *
 * @throws NullPointerException if the specified element is null
 */
public boolean offer(E e) {
    checkNotNull(e); // 对请求数据做判断
    final ReentrantLock lock = this.lock;
    lock.lock(); // 添加重入锁
    try {
        if (count == items.length) // 判断队列长度,如果队列长度等于数组长度,表示满了直接返回 false
            return false;
        else {
            enqueue(e); // 队列没满,直接调用 enqueue 将元素添加到队列中
            return true;
        }
    } finally {
        lock.unlock();
    }
}

4.enqueue(最核心的逻辑)
这个是最核心的逻辑,方法内部通过 putIndex 索引直接将元素添加到数组 items

/**
 * Inserts element at current put position, advances, and signals.
 * Call only when holding lock.
 */
private void enqueue(E x) {
    // assert lock.getHoldCount() == 1;
    // assert items[putIndex] == null;
    final Object[] items = this.items;
    items[putIndex] = x; //通过 putIndex 对数据赋值
    if (++putIndex == items.length) // 当putIndex 等于数组长度时,将 putIndex 重置为 0
        putIndex = 0;
    count++; //记录队列元素的个数
    notEmpty.signal(); //唤醒处于等待状态下的线程,表示当前队列中的元素不为空,如果存在消费者线程阻塞,就可以开始取出元素
}

putIndex 为什么会在等于数组长度的时候重新设置为 0?
因为 ArrayBlockingQueue 是一个 FIFO 的队列,队列添加元素时,是从队尾获取 putIndex 来存储元素,当 putIndex等于数组长度时,下次就需要从数组头部开始添加了。

5.put 方法
put 方法和 add 方法功能一样,差异是 put 方法如果队列满了,会阻塞。

/**
 * Inserts the specified element at the tail of this queue, waiting
 * for space to become available if the queue is full.
 *
 * @throws InterruptedException {@inheritDoc}
 * @throws NullPointerException {@inheritDoc}
 */
public void put(E e) throws InterruptedException {
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
// 这个也是获得锁,但是和 lock 的区别是,这个方法优先允许在等待时由其他线程调用等待线程的 interrupt 方法
// 来中断等待直接返回。而 lock 方法是尝试获得锁成功后才响应中断
    lock.lockInterruptibly();
    try {
        while (count == items.length)
            notFull.await(); //队列满了的情况下,当前线程将会被 notFull 条件对象挂起加到等待队列中
        enqueue(e);
    } finally {
        lock.unlock();
    }
}

6.take 方法
take 方法是一种阻塞获取队列中元素的方法,有就删除没有就阻塞。
注意这个阻塞是可以中断的,如果队列没有数据那么就加入 notEmpty 条件队列等待(有数据就直接取走,方法结束);
如果有新的 put 线程添加了数据,那么 put 操作将会唤醒 take 线程,执行 take 操作。

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == 0)
            notEmpty.await(); //如果队列为空的情况下,直接通过 await 方法阻塞
        return dequeue();
    } finally {
        lock.unlock();
    }
}

如果队列中添加了元素,那么这个时候,会在 enqueue 中调用 notempty.signal 唤醒 take 线程来获得元素

7.dequeue 方法
这个是出队列的方法,主要是删除队列头部的元素并发返回给客户端,takeIndex,是用来记录拿数据的索引值。

/**
 * Extracts element at current take position, advances, and signals.
 * Call only when holding lock.
 */
private E dequeue() {
    // assert lock.getHoldCount() == 1;
    // assert items[takeIndex] != null;
    final Object[] items = this.items;
    @SuppressWarnings("unchecked")
    E x = (E) items[takeIndex]; // 默认获取 0 位置的元素
    items[takeIndex] = null; // 将该位置的元素设置为空
    if (++takeIndex == items.length) // 这里的作用也是一样,如果拿到数组的最大值,那么重置为 0,继续从头部位置开始获取数据
        takeIndex = 0;
    count--; //记录 元素个数递减
    if (itrs != null)
        itrs.elementDequeued(); //同时更新迭代器中的元素数据
    notFull.signal(); //触发 因为队列满了以后导致的被阻塞的线程
    return x;
}

8.remove 方法

/**
 * Removes a single instance of the specified element from this queue,
 * if it is present.  More formally, removes an element {@code e} such
 * that {@code o.equals(e)}, if this queue contains one or more such
 * elements.
 * Returns {@code true} if this queue contained the specified element
 * (or equivalently, if this queue changed as a result of the call).
 *
 * <p>Removal of interior elements in circular array based queues
 * is an intrinsically slow and disruptive operation, so should
 * be undertaken only in exceptional circumstances, ideally
 * only when the queue is known not to be accessible by other
 * threads.
 *
 * @param o element to be removed from this queue, if present
 * @return {@code true} if this queue changed as a result of the call
 */
public boolean remove(Object o) {
    if (o == null) return false;
    final Object[] items = this.items; //获取数组元素
    final ReentrantLock lock = this.lock;
    lock.lock(); //获得锁
    try {
        if (count > 0) { //如果队列不为空
            final int putIndex = this.putIndex; //获取下一个要添加元素时的索引
            int i = takeIndex; //获取当前要被移除的元素的索引
            do {
                if (o.equals(items[i])) { //从takeIndex 下标开始,找到要被删除的元素
                    removeAt(i); //移除指定元素
                    return true;//返回执行结果
                }
		  //当前删除索引执行加 1 后判断是否与数组长度相等,若为 true,说明索引已到数组尽头,将 i 设置为 0
                if (++i == items.length)
                    i = 0;
            } while (i != putIndex); //继续查找,直到找到最后一个元素
        }
        return false;
    } finally {
        lock.unlock();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值