前言
好,接下来看BlockingQueue。
正文
什么是BlockingQueue?
BlockingQueue就是阻塞队列,它是继承了Queue的一个接口,它在检索和插入元素时,如果条件不满足,会阻塞等待,直到满足条件,继续执行。
BlockingQueue的结构
Interface BlockingQueue<E>
参数类型
E - 此集合中保存的元素的类型
All Superinterfaces:
Collection <E>, Iterable <E>, Queue <E>
All Known Subinterfaces:
BlockingDeque <E>, TransferQueue <E>
所有已知实现类:
ArrayBlockingQueue , DelayQueue , LinkedBlockingDeque , LinkedBlockingQueue , LinkedTransferQueue , PriorityBlockingQueue , SynchronousQueue
介绍
BlockingQueue的方法以四种形式存在,处理操作现在可能无法满足,但将来可能会在某一点满足:
- 1、抛出异常
- 2、基于操作返回特殊值(null或false)
- 3、阻塞当前线程,直到该操作成功
- 4、在放弃前会持续阻塞一个给定的最大时间
下表是对这些方法的一些概述:
Throws exception | Special value | Blocks | Times out | |
Insert | add(e) | offer(e) | put(e) | offer(e, time, unit) |
Remove | remove() | poll() | take() | poll(time, unit) |
Examine | element() | peek() | not applicable | not applicable |
方法
BlockingQueue定义的方法如下:
注意点
- BlockingQueue不支持获取null元素。
- 实现类中如果尝试调用add或put或offer方法来插入一个null,会抛出NullPointerException异常。
- null是作为poll操作失败的一个特殊值的。
- BlockingQueue可能是容量有限的。
- BlockingQueue的实现类主要被设计来用于生产者-消费者队列,但也支持Collection接口。因此,例如,可以使用remove(x)从队列中删除任意元素。 然而,这样的操作通常不能非常有效地执行,并且仅用于偶尔使用,例如当排队的消息被取消时。
- BlockingQueue的实现类是线程安全的。
- 所有排队方法使用内部锁或其他形式的并发控制在原子上实现其效果。
- 然而,大量元素的集合操作,例如addAll,contailsAll,retailAll和removeAll,不必要实现原子上的操作,除非在实现类中特别规定了。所以,比如addAll方法,可能在插入了一些元素后,失败了,抛出异常了。