1.BlockingQueue定义的常用方法如下
  抛出异常 特殊值 阻塞 超时
插入 add(e) offer(e) put(e) offer(e,time,unit)
移除 remove() poll() take() poll(time,unit)
检查 element() peek() 不可用 不可用
 

1)add(anObject):把anObject加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则招聘异常

2)offer(anObject):表示如果可能的话,将anObject加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则返回false.

3)put(anObject):把anObject加到BlockingQueue里,如果BlockQueue没有空间,则调用此方法的线程被阻断直到BlockingQueue里面有空间再继续.

4)poll(time):取走BlockingQueue里排在首位的对象,若不能立即取出,则可以等time参数规定的时间,取不到时返回null

5)take():取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到Blocking有新的对象被加入为止

其中:BlockingQueue 不接受null 元素。试图addput 或offer 一个null 元素时,某些实现会抛出NullPointerExceptionnull 被用作指示poll 操作失败的警戒值。 
 

2、BlockingQueue的几个注意点

【1】BlockingQueue 可以是限定容量的。它在任意给定时间都可以有一个remainingCapacity,超出此容量,便无法无阻塞地put 附加元素。没有任何内部容量约束的BlockingQueue 总是报告Integer.MAX_VALUE 的剩余容量。

【2】BlockingQueue 实现主要用于生产者-使用者队列,但它另外还支持Collection 接口。因此,举例来说,使用remove(x) 从队列中移除任意一个元素是有可能的。然而,这种操作通常 会有效执行,只能有计划地偶尔使用,比如在取消排队信息时。

【3】BlockingQueue 实现是线程安全的。所有排队方法都可以使用内部锁或其他形式的并发控制来自动达到它们的目的。然而,大量的 Collection 操作(addAllcontainsAllretainAll 和removeAll没有 必要自动执行,除非在实现中特别说明。因此,举例来说,在只添加了c 中的一些元素后,addAll(c) 有可能失败(抛出一个异常)。

【4】BlockingQueue 实质上不支持使用任何一种“close”或“shutdown”操作来指示不再添加任何项。这种功能的需求和使用有依赖于实现的倾向。例如,一种常用的策略是:对于生产者,插入特殊的end-of-stream 或poison 对象,并根据使用者获取这些对象的时间来对它们进行解释。
 
3、简要概述BlockingQueue常用的四个实现类

 

1)ArrayBlockingQueue:规定大小的BlockingQueue,其构造函数必须带一个int参数来指明其大小.其所含的对象是以FIFO(先入先出)顺序排序的.

2)LinkedBlockingQueue:大小不定的BlockingQueue,若其构造函数带一个规定大小的参数,生成的BlockingQueue有大小限制,若不带大小参数,所生成的BlockingQueue的大小由Integer.MAX_VALUE来决定.其所含的对象是以FIFO(先入先出)顺序排序的

3)PriorityBlockingQueue:类似于LinkedBlockQueue,但其所含对象的排序不是FIFO,而是依据对象的自然排序顺序或者是构造函数的Comparator决定的顺序.

4)SynchronousQueue:特殊的BlockingQueue,对其的操作必须是放和取交替完成的.

    
其中LinkedBlockingQueue和ArrayBlockingQueue比较起来,它们背后所用的数据结构不一样,导致LinkedBlockingQueue的数据吞吐量要大于ArrayBlockingQueue,但在线程数量很大时其性能的可预见性低于ArrayBlockingQueue.  
 
下面主要看一下ArrayBlockingQueue的源码:
  1. public boolean offer(E e) {
  2. if (e == null) throw new NullPointerException();
  3. final ReentrantLock lock = this.lock;//每个对象对应一个显示的锁
  4. lock.lock();//请求锁直到获得锁(不可以被interrupte)
  5. try {
  6. if (count == items.length)//如果队列已经满了
  7. return false;
  8. else {
  9. insert(e);
  10. return true;
  11. }
  12. } finally {
  13. lock.unlock();//
  14. }
  15. }
  16. 看insert方法:
  17. private void insert(E x) {
  18. items[putIndex] = x;
  19. //增加全局index的值。
  20. /*
  21. Inc方法体内部:
  22. final int inc(int i) {
  23. return (++i == items.length)? 0 : i;
  24. }
  25. 这里可以看出ArrayBlockingQueue采用从前到后向内部数组插入的方式插入新元素的。如果插完了,putIndex可能重新变为0(在已经执行了移除操作的前提下,否则在之前的判断中队列为满)
  26. */
  27. putIndex = inc(putIndex);
  28. ++count;
  29. notEmpty.signal();//wake up one waiting thread
  30. }
 
  1. public void put(E e) throws InterruptedException {
  2. if (e == null) throw new NullPointerException();
  3. final E[] items = this.items;
  4. final ReentrantLock lock = this.lock;
  5. lock.lockInterruptibly();//请求锁直到得到锁或者变为interrupted
  6. try {
  7. try {
  8. while (count == items.length)//如果满了,当前线程进入noFull对应的等waiting状态
  9. notFull.await();
  10. } catch (InterruptedException ie) {
  11. notFull.signal(); // propagate to non-interrupted thread
  12. throw ie;
  13. }
  14. insert(e);
  15. } finally {
  16. lock.unlock();
  17. }
  18. }
 
  1. public boolean offer(E e, long timeout, TimeUnit unit)
  2. throws InterruptedException {
  3. if (e == null) throw new NullPointerException();
  4. long nanos = unit.toNanos(timeout);
  5. final ReentrantLock lock = this.lock;
  6. lock.lockInterruptibly();
  7. try {
  8. for (;;) {
  9. if (count != items.length) {
  10. insert(e);
  11. return true;
  12. }
  13. if (nanos <= 0)
  14. return false;
  15. try {
  16. //如果没有被 signal/interruptes,需要等待nanos时间才返回
  17. nanos = notFull.awaitNanos(nanos);
  18. } catch (InterruptedException ie) {
  19. notFull.signal(); // propagate to non-interrupted thread
  20. throw ie;
  21. }
  22. }
  23. } finally {
  24. lock.unlock();
  25. }
  26. }
 
  1. public boolean add(E e) {
  2. return super.add(e);
  3. }
  4. 父类:
  5. public boolean add(E e) {
  6. if (offer(e))
  7. return true;
  8. else
  9. throw new IllegalStateException("Queue full");
  10. }
 
该类中有几个实例变量:takeIndex/putIndex/count
  1. 用三个数字来维护这个队列中的数据变更:
  2. /** items index for next take, poll or remove */
  3. private int takeIndex;
  4. /** items index for next put, offer, or add. */
  5. private int putIndex;
  6. /** Number of items in the queue */
  7. private int count;
 
 
转自:http://blog.csdn.net/vernonzheng/article/details/8247564

BlockingQueue深入分析(转)的更多相关文章

  1. BlockingQueue深入分析

    1.BlockingQueue定义的常用方法如下   抛出异常 特殊值 阻塞 超时 插入 add(e) offer(e) put(e) offer(e,time,unit) 移除 remove() p ...

  2. Java多线程(五)之BlockingQueue深入分析

    一.概述: BlockingQueue作为线程容器,可以为线程同步提供有力的保障.   二.BlockingQueue定义的常用方法 1.BlockingQueue定义的常用方法如下:  1)add( ...

  3. BlockingQueue

    BlockingQueue的使用 http://www.cnblogs.com/liuling/p/2013-8-20-01.html BlockingQueue深入分析 http://blog.cs ...

  4. paip.java 线程无限wait的解决

    paip.java  线程无限wait的解决 jprofl>threads>thread dump> 查看棉线程执行的code stack... 估计是.比如.BlockingQue ...

  5. JDK源码分析—— ArrayBlockingQueue 和 LinkedBlockingQueue

    JDK源码分析—— ArrayBlockingQueue 和 LinkedBlockingQueue 目的:本文通过分析JDK源码来对比ArrayBlockingQueue 和LinkedBlocki ...

  6. 《java并发编程实战》读书笔记4--基础构建模块,java中的同步容器类&并发容器类&同步工具类,消费者模式

    上一章说道委托是创建线程安全类的一个最有效策略,只需让现有的线程安全的类管理所有的状态即可.那么这章便说的是怎么利用java平台类库的并发基础构建模块呢? 5.1 同步容器类 包括Vector和Has ...

  7. 并发编程 20—— AbstractQueuedSynchronizer 深入分析

    Java并发编程实践 目录 并发编程 01—— ThreadLocal 并发编程 02—— ConcurrentHashMap 并发编程 03—— 阻塞队列和生产者-消费者模式 并发编程 04—— 闭 ...

  8. 并发编程 06—— CompletionService :Executor 和 BlockingQueue

    Java并发编程实践 目录 并发编程 01—— ThreadLocal 并发编程 02—— ConcurrentHashMap 并发编程 03—— 阻塞队列和生产者-消费者模式 并发编程 04—— 闭 ...

  9. 3W字干货深入分析基于Micrometer和Prometheus实现度量和监控的方案

    前提 最近线上的项目使用了spring-actuator做度量统计收集,使用Prometheus进行数据收集,Grafana进行数据展示,用于监控生成环境机器的性能指标和业务数据指标.一般,我们叫这样 ...

随机推荐

  1. 使用Pip安装distribute、nose、virtualenv

    1 安装distribute sudo pip install distribute 2 安装nose sudo pip install nose 3 安装virtualenv sudo pip in ...

  2. light

    Unity5中lightmap的坑 http://blog.csdn.net/langresser_king/article/details/48914901 Unity中光照贴图一二坑及解决办法 h ...

  3. 线程安全的无锁RingBuffer的实现

    这里的线程安全,是指一个读线程和一个写线程,读写两个线程是安全的,而不是说多个读线程和多个写线程是安全的.. 在程序设计中,我们有时会遇到这样的情况,一个线程将数据写到一个buffer中,另外一个线程 ...

  4. 在Application中集成Microsoft Translator服务之优化

    在一篇文章中我们已经实现了功能,但是一个明显的问题是响应时间非常长,用户体验非常糟糕,这篇文章将带你找出问题所在并进行优化 为了找出追魁祸首,这里使用 System.Diagnostics.Stopw ...

  5. Bootstrap学习------按钮

    Bootstrap为我们提供了按钮组的样式,博主写了几个简单的例子,以后也许用的到. 效果如下 代码如下 <!DOCTYPE html> <html> <head> ...

  6. JUnit4 中@AfterClass @BeforeClass @after @before的区别对比

    JUnit4使用Java5中的注解(annotation),以下是JUnit4常用的几个annotation: @Before:初始化方法   对于每一个测试方法都要执行一次(注意与BeforeCla ...

  7. ActiveMQ启动多个broker

    具体步骤如下: 1.把activemq目录下的conf文件复制一份,叫做conf2, 命令: cp -r conf conf2 2.修改conf2目录下的activemq.xml文件 a.修改brok ...

  8. nyoj 106背包问题(贪心专题)

    背包问题 时间限制:3000 ms  |  内存限制:65535 KB 难度:3   描述 现在有很多物品(它们是可以分割的),我们知道它们每个物品的单位重量的价值v和重量w(1<=v,w< ...

  9. Linux下忘记MySQL的root密码的解决方法

    恢复方法之一 1.首先确认服务器出于安全的状态,也就是没有人能够任意地连接MySQL数据库. 因为在重新设置MySQL的root密码的期间,MySQL数据库完全出于没有密码保护的 状态下,其他的用户也 ...

  10. 如何让Linux定时任务crond以秒为单位执行(如每隔3秒)

    需要用到Shell脚本每隔3秒钟去监控一个软件进程的运行状态,发现crond似乎只支持到分,不知道秒,怎么办呢? 第一种方法: 当然首先想到的是写一个触发的脚本,在触发脚本中使用死循环来解决此问题,如 ...