一:简介
阻塞队列:从定义上来说是队列的一种,那么肯定是一个先进先出(FIFO)的数据结构。与普通队列不同的是,它支持两个附加操作,即阻塞添加和阻塞删除方法。
阻塞添加:当阻塞队列是满时,往队列里添加元素的操作将被阻塞。
阻塞移除:当阻塞队列是空时,从队列中获取元素/删除元素的操作将被阻塞。
二:java中对阻塞队列的定义
BlockingQueue接口与Queue接口【Queue 和 BlockingQueue 都是在 Java 5 中加入的】
1:Queue接口
public interface Queue<E> extends Collection<E> {
//添加一个元素,添加成功返回true, 如果队列满了,就会抛出异常
boolean add(E e);
//添加一个元素,添加成功返回true, 如果队列满了,返回false
boolean offer(E e);
//返回并删除队首元素,队列为空则抛出异常
E remove();
//返回并删除队首元素,队列为空则返回null
E poll();
//返回队首元素,但不移除,队列为空则抛出异常
E element();
//获取队首元素,但不移除,队列为空则返回null
E peek();
}
2:BlockingQueue接口
源码展示:
public interface BlockingQueue<E> extends Queue<E> {
boolean add(E e);
boolean offer(E e);
void put(E e) throws InterruptedException;
boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException;
E take() throws InterruptedException;
E poll(long timeout, TimeUnit unit) throws InterruptedException;
int remainingCapacity();
boolean remove(Object o);
public boolean contains(Object o);
int drainTo(Collection<? super E> c);
int drainTo(Collection<? super E> c, int maxElements);
}
分析说明:
(1)BlockingQueue 继承了 Queue 接口
,是队列的一种。阻塞队列(BlockingQueue)是一个在队列基础上又支持了两个附加操作的队列,两个附加操作:
- 支持阻塞的插入方法
put
: 队列满时,队列会阻塞插入元素的线程,直到队列不满。 - 支持阻塞的移除方法
take
: 队列空时,获取元素的线程会等待队列变为非空。
(2)BlockingQueue和JDK集合包中的Queue接口
兼容,同时在其基础上增加了阻塞功能:
入队