3.11 BlockingQueue
BlockingQueue接口表示阻塞队列,是Java并发包中阻塞队列的接口定义规范,阻塞队列意味着对于该队列的操作是线程安全的,当多个线程存放元素进入队列或者从队列中取出元素都是线程安全的。阻塞队列的操作和普通队列没有区别,主要是加了线程安全控制,其工作原理如下图。
3.11.1 BlockingQueue接口继承关系
BlockingQueue是继承自java集合框架中的Queue接口。
3.11.2 BlockingQueue接口源码
可以看到BlockingQueue继承自Queue接口,Queue接口也顺便复习下,关于集合框架队列的讲述可以在笔者集合篇.中找到。
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;
boolean remove(Object o);
//
int remainingCapacity();
public boolean contains(Object o);
int drainTo(Collection<? super E> c);
int drainTo(Collection<? super E> c, int maxElements);
}
drainTo(Collection<? super E> c)方法表示将队列元素全部移除并且放入集合c中,该方法相当于队列全部弹出。
public interface Queue<E> extends Collection<E> {
/**
* 添加元素,和offer方法不同的是add方法可能抛出队列状态异常
*/
boolean add(E e);
/**
* 添加元素
*/
boolean offer(E e);
/**
* 和poll()方法相同也是取出头部元素,区别在于队列为空抛出异常
*/
E remove();
/**
* 头部取出元素
*/
E poll();
/**
* 和peek()方法相同,获取队列头部元素,区别在于当队列为空会抛出异常
*/
E element();
/**
* 获取队列头部元素,不对队列进行修改
*/
E peek();
}
BlockingQueue的offer,poll方法实现了重载,可设置等待时间,其余相关操作概率完全一样。