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;
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);
}
这个接口定义的方法有几和Queue接口定义的一致,这里主要的区别在于,假设队列是空的,出队操作会怎么执行,包括抛异常,返回指定值和阻塞等待。看下面的表格很清晰。
抛异常 | 指定值 | 阻塞 | 带超时的阻塞 | |
---|---|---|---|---|
插入 | add(e) | offer(e) | put(e) | offer(e,time,unit) |
移除 | remove() | poll() | take() | poll(time,unit) |
测试 | element() | peak() |
接下来看它的几个实现类,说明一下,BlockingQueue和它的实现类都是在java.util.concurrent包下的,肯定要保证线程安全的。