介绍
阻塞队列(BlockingQueue)是一个支持两个附加操作的队列。这两个附加的操作是:在队列为空时,获取元素的线程会等待队列变为非空。当队列满时,存储元素的线程会等待队列可用。阻塞队列常用于生产者和消费者的场景,生产者是往队列里添加元素的线程,消费者是从队列里拿元素的线程。阻塞队列就是生产者存放元素的容器,而消费者也只从容器里拿元素。
方法
方法类型 | 抛出异常 | 特殊值 | 阻塞 | 超时 |
---|---|---|---|---|
插入 | add(e) | offer(e) | put(e) | offer(e,time,unit) |
移除 | remove() | poll() | take() | poll(time,unit) |
检查 | element() | peek() | 不可用 | 不可用 |
构造函数
默认非公平锁
线程安全,采用了ReentrantLock
/**
* Creates an {@code ArrayBlockingQueue} with the given (fixed)
* capacity and default access policy.
*
* @param capacity the capacity of this queue
* @throws IllegalArgumentException if {@code capacity < 1}
*/
public ArrayBlockingQueue(int capacity) {
this(capacity, false);
}
源码
public interface BlockingQueue<E> extends Queue<E> {
/**
* 将给定元素设置到队列中,如果设置成功返回true,
* 空间不足,抛出IllegalStateException异常。如果是向限定了长度的队列中设置值,推荐使用offer()方法。
*/
boolean add(E e);
/**
* 将给定的元素设置到队列中,如果设置成功返回true, 空间不足返回false。
*/
boolean offer(E e);
/**
* 将元素设置到队列中,如果空间不足,该方法会一直阻塞,直到队列中有多余的空间。
*/
void put(E e) throws InterruptedException;
/**
* 将给定元素设置到队列中,空间不足,至多等待给定的时间,如果设置成功返回true, 否则返回false。
*/
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);
}
相关类
-
ArrayBlockingQueue
基于数组的先进先出队列,bounded(有界)
- LinkedBlockingQueue
基于链表的先进先出队列,optionally-bounded( 可选有界 )
- PriorityBlockingQueue
基于数组的先进先出队列,一个支持线程优先级排序的无界队列,默认自然序进行排序,也可以自定义实现compareTo()方法来指定元素排序规则,不能保证同优先级元素的顺序,unbounded(无界)