java version “1.8.0_221”
Java(TM) SE Runtime Environment (build 1.8.0_221-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.221-b11, mixed mode)

介绍

BlockingQueue 是一个接口,并且它还继承了 Queue 接口,在继承 Queue 接口的基础上,增加了一些 阻塞式 的操作。

BlockingQueue 中的成员方法有四种形式,分别满足各个场景的需求:

Throws excepiton 抛出异常 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()
  • element 和 peek 仅在 Queue 接口中定义,他们都是返回表头元素,唯一不同的是当队列为空时,element() 方法会抛出 NoSuchElementException。

  • BlockingQueue 不接受 NULL 元素,否则会抛出 NullPointerException,还有就是 poll 操作失败时,会返回 NULL。

  1. public interface BlockingQueue<E> extends Queue<E> {
  2. /**************** 插入元素 *******************/
  3. /**
  4. * 添加元素,成功返回 true;若队列容量满,抛出 IllegalStateException 异常。当使用容量受限的队列时,推荐使用 offer(E e)
  5. */
  6. boolean add(E e);
  7. /**
  8. * 插入成功返回 true,否则返回 false;这个方法好于 add(),add() 插入失败会抛出异常
  9. */
  10. boolean offer(E e);
  11. /**
  12. * 空间足够时直接插入,空间不足时进行等待,直到有空间插入
  13. */
  14. void put(E e) throws InterruptedException;
  15. /**
  16. * 带超时时间的插入,true-插入成功,false-直到超时时间过了还没有插入进去
  17. * 等待期间被 interrupted 时,抛出 InterruptedException 异常
  18. * 若某些不该添加到这个队列的元素被添加进去时,抛出 IllegalArgumentException 异常
  19. */
  20. boolean offer(E e, long timeout, TimeUnit unit)
  21. throws InterruptedException;
  22. /**************** 删除元素 *******************/
  23. /**
  24. * 删除表头元素,若表头元素还不可用,将等待其可用
  25. * 等待期间被 interrupted 时,抛出 InterruptedException 异常
  26. */
  27. E take() throws InterruptedException;
  28. /**
  29. * 带超时时间移除表头元素;若超过时间都没有移除成功,返回 null
  30. * 等待期间被 interrupted 时,抛出 InterruptedException 异常
  31. */
  32. E poll(long timeout, TimeUnit unit)
  33. throws InterruptedException;
  34. /**
  35. * 移除队列中指定元素(可能存在一个或者多个),若队列发生了更改,返回 true。
  36. */
  37. boolean remove(Object o);
  38. /**************** 其它方法 *******************/
  39. /**
  40. * 返回队列在没有内存或者资源限制下,可以无阻塞地添加元素的数量,一般为 Integer.MAX_VALUE。
  41. * 由于同一时刻可能有其它线程也在操作这个队列,所以他的返回值不是一直都是可信地。
  42. */
  43. int remainingCapacity();
  44. /**
  45. * 队列包含该元素(一个或多个, equals 比较元素是否相等)返回 true
  46. */
  47. public boolean contains(Object o);
  48. /**
  49. * 移动队列元素到集合 c 中,这个操作比重复的 poll + add 更有效率。
  50. * 但是此过程可能发生异常,并且如果方法执行过程中,c 发生了变化,将会造成不可预知的结果。
  51. */
  52. int drainTo(Collection<? super E> c);
  53. /**
  54. * 移动队列中 maxElements 个元素到集合 c 中
  55. */
  56. int drainTo(Collection<? super E> c, int maxElements);
  57. }