在讲阻塞式队列之前,首先理解什么是JUC。
JUC是(java.util.concurrent的简称),是java1.5提供的一个处理线程的工具包及其子包。JUC的主要内容包括:阻塞式队列、并发映射、锁、执行器服务、原子性操作。本次给大家首先介绍的就是其中的阻塞式队列。
阻塞式队列(Blocking Queue)
顾名思义,“阻塞式”是对“队列”的形容,主语还是“队列”。所以它满足队列的基本特点:FIFO(FIRST IN FIRST OUT——先进先出)。除此之外,它在使用之前需要确定容量,且确定之后,容量不可变。
既然还提到了“阻塞”,那它一定有阻塞相关的特性:
1.如果队列为空,尝试获取元素会阻塞。
2.如果队列已满,尝试添加元素会阻塞。
查询java的api文档:
BolockingQueue是一个接口,继承了Collection、Iterable 、Queue接口,直接实现类主要有:ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue等等。
对其中一个有代表性的ArrayBlockingQueue实现类进行简单介绍。
阻塞式顺序队列—ArrayBlockingQueue
作为一个容器,我们使用它的目地无法就是对它增、删、改、查,来实现对数据的操作。
ArrayBlockingQueue提供了三类主要的添加数据的方法,分别为:add put 以及offer。
用代码演示它们之间的区别。
add
@Test
public void arayBlockingQueue() throws InterruptedException {
//使用时需要指定容量
BlockingQueue<Integer> arrbq=new ArrayBlockingQueue(5);
arrbq.add(1);
arrbq.add(4);
arrbq.add(5);
arrbq.add(7);
arrbq.add(8);
System.out.println(arrbq);
//数据已满,继续添加元素
arrbq.add(8);
System.out.println(arrbq);
}
执行效果:add方法是非阻塞的,如果队列已满,继续添加元素会抛出Queue full异常:
put
//数据已满,继续添加元素
arrbq.put(8);
执行效果:add方法是阻塞的,如果队列已满,继续添加元素会产生阻塞:
offer
//数据已满,继续添加元素
arrbq.offer(8);
执行效果:offer方法是非阻塞的,如果队列已满,继续添加不会报错,而且新添加的元素也不会添加到队列中(存在返回值,添加成功返回true ,添加失败返回false):
offer还重载了一个定时阻塞的方法,相信一看便懂,不再赘述。
除了添加元素,相对应的还有删除元素。删除元素的主要方法有:remove take poll
remove
/**
* Retrieves and removes the head of this queue. This method differs
* from {@link #poll poll} only in that it throws an exception if this
* queue is empty.
*
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
*/
从源码的解释可以看出,该方法将移除队首元素,如果队列为空,抛出NoSuchElementException异常。
take
/**
* Retrieves and removes the head of this queue, waiting if necessary
* until an element becomes available.
*
* @return the head of this queue
* @throws InterruptedException if interrupted while waiting
*/
移除队首元素,必要时将等待(也就是会产生阻塞),直到有元素可以获取。
poll
/**
* Retrieves and removes the head of this queue,
* or returns {@code null} if this queue is empty.
*
* @return the head of this queue, or {@code null} if this queue is empty*/
*
移除队首元素,如果有则移除,没有则返回null。也是非阻塞的。
和offer对应,poll也重载了一个定时阻塞的方法:
总结
抛出异常 | 返回指定值 | 永久阻塞 | 定时阻塞 | |
---|---|---|---|---|
添加 | 如果队列已满,add抛出IllegalStateException | offer 添加成功返回 true ,添加失败 false | put | offer |
移除 | 如果队列为空,remove抛出 NoSuchElementException | poll 队列为空返回null | take | poll |