【第二十篇】阻塞队列之ArrayBlockingQueue原理简析【重点】

1.1 ArrayBlockingQueue介绍

BlockingQueue是一个阻塞队列,在高并发场景是用得非常多的,比如在线程池中:

如果运行线程数目大于核心线程数目时,也会尝试把新加入的线程放到一个BlockingQueue中去。

队列的特性就是先进先出很容易理解,在java里头它的实现类主要有下图的几种,其中最常用到的是ArrayBlockingQueue、LinkedBlockingQueue及SynchronousQueue这三种,本文我们主要来讲解ArrayBlockingQueue。
在这里插入图片描述
BlockingQueue它主要的方法有
在这里插入图片描述

ArrayBlockingQueue是数组实现的线程安全的有界的阻塞队列,此队列按 FIFO(先进先出)原则对元素进行排序。 队列的头部是在队列中存在时间最长的元素,队列的尾部是在队列中存在时间最短的元素

  ArrayBlockingQueue 是一个有界队列,有界也就意味着,它不能够存储无限多数量的对象。所以在创建 ArrayBlockingQueue 时,必须要给它指定一个队列的大小

1.2 ArrayBlockingQueue源码解析

我们来看一下几个总要的方法:

  • add(E e):把 e 加到 BlockingQueue 里,即如果 BlockingQueue 可以容纳,则返回 true,否则报异常
  • offer(E e):表示如果可能的话,将 e 加到 BlockingQueue 里,即如果 BlockingQueue 可以容纳,则返回 true,否则返回 false
  • put(E e):把 e 加到 BlockingQueue 里,如果 BlockQueue 没有空间,则调用此方法的线程被阻断直到 BlockingQueue 里面有空间再继续
  • poll(time):取走 BlockingQueue 里排在首位的对象,若不能立即取出,则可以等 time 参数规定的时间,取不到时返回 null
  • take():取走 BlockingQueue 里排在首位的对象,若 BlockingQueue 为空,阻断进入等待状态直到 Blocking 有新的对象被加入为止
  • remainingCapacity():剩余可用的大小。等于初始容量减去当前的 size

1.2.1 主要属性

//数据数组
final Object[] items;

//头节点下标
int takeIndex;

//尾节点下标
int putIndex;

//元素个数
int count;

//独占锁,入队和出队公用一个lock,说明不能同时出队和入队
final ReentrantLock lock;

//出队等待条件队列
private final Condition notEmpty;
//入队等待条件队列
private final Condition notFull;

1.2.2 初始化

public ArrayBlockingQueue(int capacity) {
    //false默认lock为非公平锁
    this(capacity, false);
}
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.2.3 offer()

public boolean offer(E e) {
    //private static void checkNotNull(Object v) {
    //    if (v == null)
    //        throw new NullPointerException();
    //}
    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();
    }
}
//入队
private void enqueue(E x) {
    final Object[] items = this.items;
    
    items[putIndex] = x;
    //如果putIndex超出数组范围了,就置为0
    if (++putIndex == items.length)
        putIndex = 0;
    count++;
    //唤醒等待出队节点
    notEmpty.signal();
}

1.2.4 add()

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

通过代码可以看出,当队列满的时候,add()会抛出异常,而offer()就是返回false而已。

1.2.5 put()

`public void put(E e) throws InterruptedException {
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        //如果队列满了,阻塞再notFull等待队列中
        while (count == items.length)
            notFull.await();
        enqueue(e);
    } finally {
        lock.unlock();
    }
}

put()和offer()的区别是,put()在队列满的时候,会阻塞。

1.2.6 poll()

public E poll() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        //如果队列为空,返回null。
        return (count == 0) ? null : dequeue();
    } finally {
        lock.unlock();
    }
}
private E dequeue() {
    
    final Object[] items = this.items;
    @SuppressWarnings("unchecked")
    E x = (E) items[takeIndex];
    items[takeIndex] = null;
    //如果takeIndex等于items.length,将takeIndex = 0
    if (++takeIndex == items.length)
        takeIndex = 0;
    count--;
    //更新迭代器
    if (itrs != null)
        itrs.elementDequeued();
    //唤醒等待入队线程
    notFull.signal();
    return x;
}

1.2.7 take()

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        //如果队列为空,阻塞在notEmpty等待队列中
        while (count == 0)
            notEmpty.await();
        return dequeue();
    } finally {
        lock.unlock();
    }
}

take()和poll()的区别就是当队列为空的时候,take()会阻塞。

1.2.8 peek()

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

1.3 总结

ArrayBlockingQueue和LinkedBlockingQueue有以下区别:

1、ArrayBlockingQueue基于数组,LinkedBlockingQueue基于链表

2、ArrayBlockingQueue只有一个ReentrantLock,出队和入队是不能同时进行的,而LInkedBlockingQueue有两个ReentrantLock,出队和入队是可以同时进行的。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋分的秋刀鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值