玖叶教程网

前端编程开发入门

阻塞队列之ArrayBlockingQueue详解

1 简介

ArrayBlockingQueue是基于数组的阻塞队列。数组是要指定长度的,所以使用 ArrayBlockingQueue 时必须指定长度,也就是它是一个有界队列。它实现了 BlockingQueue 接口,有着队列、集合以及阻塞队列的所有方法。

ArrayBlockingQueue是线程安全的,内部使用ReentrantLock来保证。ArrayBlockingQueue支持对生产者线程和消费者线程进行公平的调度。当然默认情况下是不保证公平性的,因为公平性通常会降低吞吐量,但是可以减少可变性和避免线程饥饿问题。

下面我通过测试用例以及对应的方法源码来讲解下。

2 测试用例

2.1 初始化

ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<>(1);

2.2 add方法

使用:

// 代码
@Test
public void add(){
  abq.add("面试题解析");
  abq.add("面试题解析");
}
// 输出
java.lang.IllegalStateException: Queue full
	at java.util.AbstractQueue.add(AbstractQueue.java:98)
	at java.util.concurrent.ArrayBlockingQueue.add(ArrayBlockingQueue.java:312)
	...

源码解析:

// 1 调用ArrayBlockingQueue的add方法
public boolean add(E e) {
  return super.add(e);
}
// 2 调用java.util.AbstractQueue#add的方法
public boolean add(E e) {
  // 当offer方法返回false的时候,就抛出了Queue full的异常。
  if (offer(e))
    return true;
  else
    throw new IllegalStateException("Queue full");
}
// 3 看下offer方法
public boolean offer(E e) {
  checkNotNull(e);
  final ReentrantLock lock = this.lock;
  lock.lock();
  try {
    // 当第二次调用的时候,元素个数和数组长度相等,返回false
    if (count == items.length)
      return false;
    // 当第一次调用的时候,可以加入到队列中去,这个返回true
    else {
      enqueue(e);
      return true;
    }
  } finally {
    lock.unlock();
  }
}
// 4 看下enqueue的方法,向数组中添加元素,并且元素数加一
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();
}
// 从而不难看出为啥数组大小为1,两次add元素抛出异常的原因了。

2.3 offer方法

使用:

// 代码
@Test
public void offer(){
  boolean offer1 = abq.offer("面试题解析");
  log.info(offer1);
  boolean offer2 = abq.offer("面试题解析");
  log.info(offer2);
}
// 输出
INFO - true
INFO - false

源码解析:

public boolean offer(E e) {
  checkNotNull(e);
  final ReentrantLock lock = this.lock;
  lock.lock();
  try {
    // 当第二次加入时,元素个数和数组大小相同时,返回false,可以说明为啥offer2是false
    if (count == items.length)
      return false;
    else {
      // 当第一次添加时,可以成功加入到队列,返回true,即offer1为true
      enqueue(e);
      return true;
    }
  } finally {
    lock.unlock();
  }
}

2.4 put方法

使用:

// 代码
@Test
public void put() throws Exception{
  abq.put("面试题解析");
  log.info("第一次put结束");
  abq.put("面试题解析");
  log.info("第二次put结束");
}
// 输出
INFO - 第一次put结束

由结果可以看出程序阻塞在第二次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();
  }
}

2.5 take方法

使用:

// 代码
@Test
public void take() throws Exception{
  log.info("开始take");
  String take = abq.take();
  log.info(take);
}
// 输出
INFO - 开始take

从结果可以看出take没有输出,说明阻塞在take方法上了。

源码解析:

public E take() throws InterruptedException {
  final ReentrantLock lock = this.lock;
  lock.lockInterruptibly();
  try {
    // 当元素个数为0时,程序阻塞
    while (count == 0)
      notEmpty.await();
    return dequeue();
  } finally {
    lock.unlock();
  }
}

2.6 remove方法

使用:

// 代码
@Test
public void remove(){
  abq.offer("面试题解析");
  String remove = abq.remove();
  log.info(remove);
}
// 输出
INFO - 面试题解析

可以看出remove方法返回了被remove的值。

源码解析:

public E remove() {
  	// 返回队列的首值,当队列为空时,则会报异常。
    E x = poll();
    if (x != null)
        return x;
    else
        throw new NoSuchElementException();
}

2.7 remove方法

使用:

// 代码
@Test
public void element(){
  String element = abq.element();
  log.info(element);
}
// 输出
java.util.NoSuchElementException
	at java.util.AbstractQueue.element(AbstractQueue.java:136)
	at ArrayBlockingQueueTest.element(ArrayBlockingQueueTest.java:49)
	...

说明当队列为空时,检测首值时会报错。

源码解析:

public E element() {
  // 返回队列的首值,当队列为空时,则会报异常。
  E x = peek();
  if (x != null)
    return x;
  else
    throw new NoSuchElementException();
}
// peek只会返回首值,而不会删除首值,这个是与poll的根本区别
public E peek() {
  final ReentrantLock lock = this.lock;
  lock.lock();
  try {
    return itemAt(takeIndex); // null when queue is empty
  } finally {
    lock.unlock();
  }
}
// poll方法会使用dequeue方法返回值
public E poll() {
  final ReentrantLock lock = this.lock;
  lock.lock();
  try {
    return (count == 0) ? null : dequeue();
  } finally {
    lock.unlock();
  }
}
// dequeue方法会删除首值
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;
}

2.8 remove方法

使用:

// 代码
@Test
public void peek(){
  String peek = abq.peek();
  log.info(peek);
}
// 输出
INFO - null

队列为空时,返回的是null,讲解2.7 remove时已经介绍了peek的源码,在此就不再赘述了。

2.9 remainingCapacity方法

使用:

// 代码
@Test
public void remainingCapacity(){
  int remainingCapacity = abq.remainingCapacity();
  log.info(remainingCapacity);
}
// 输出
INFO - 1

求队列的剩余容量。

源码解析:

public int remainingCapacity() {
  final ReentrantLock lock = this.lock;
  lock.lock();
  try {
    // 返回的是数组的大小减去元素的个数
    return items.length - count;
  } finally {
    lock.unlock();
  }
}

2.10 clear方法

使用:

@Test
public void clear(){
  abq.clear();
}

清空队列。

源码解析:

public void clear() {
  final Object[] items = this.items;
  final ReentrantLock lock = this.lock;
  lock.lock();
  try {
    int k = count;
    if (k > 0) {
      final int putIndex = this.putIndex;
      int i = takeIndex;
      // 循环清空所有数据
      do {
        items[i] = null;
        if (++i == items.length)
          i = 0;
      } while (i != putIndex);
      takeIndex = putIndex;
      count = 0;
      if (itrs != null)
        itrs.queueIsEmpty();
      for (; k > 0 && lock.hasWaiters(notFull); k--)
        notFull.signal();
    }
  } finally {
    lock.unlock();
  }
}

3 总结

ArrayBlockingQueue是一个阻塞队列,内部由ReentrantLock来实现线程安全,由Condition的await和signal来实现等待唤醒的功能。它的数据结构是数组,准确的说是一个循环数组(可以类比一个圆环),所有的下标在到达最大长度时自动从0继续开始。上面是主要的一些方法,在使用过程中,有什么问题,欢迎留言,随时交流,感谢支持。

【温馨提示】

点赞+收藏文章,关注我并私信回复【面试题解析】,即可100%免费领取楼主的所有面试题资料!

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言