⑴背景

阻塞队列常用于生产者消费者场景,生产者是向队列里添加元素的线程,消费者是向队列里取出元素的线程。阻塞队列的角色是供生产者存放元素,消费者取出元素的容器。

⑵阻塞队列

阻塞队列是一个支持两个附加操作的队列。(支持阻塞插入和移除方法)

①阻塞插入:当队列满时,队列会阻塞插入元素的线程,直到队列不满。

②阻塞移除:当队列空时,获取元素的线程会等待队列变为空。

  /** The queued items */
     final Object[] items;

     /** items index for next take, poll, peek or remove */
     int takeIndex;

     /** items index for next put, offer, or add */
     int putIndex;

     /** Number of elements in the queue */
     int count;

     /*
      * Concurrency control uses the classic two-condition algorithm
      * found in any textbook.
      */

     /** Main lock guarding all access */
     final ReentrantLock lock;

     /** Condition for waiting takes */
     private final Condition notEmpty;

     /** Condition for waiting puts */
     private final Condition notFull;
 /**
      * Creates an {@code ArrayBlockingQueue} with the given (fixed)
      * capacity and the specified access policy.
      *
      * @param capacity the capacity of this queue
      * @param fair if {@code true} then queue accesses for threads blocked
      *        on insertion or removal, are processed in FIFO order;
      *        if {@code false} the access order is unspecified.
      * @throws IllegalArgumentException if {@code capacity < 1}
      */
     public ArrayBlockingQueue(int capacity, boolean fair) {           //当队列容量小于等于0,会抛异常。当队列满时再继续插入,也会抛该异常
         if (capacity <= 0)
             throw new IllegalArgumentException();           //创建容量数组
         this.items = new Object[capacity];           //创建可重入锁与阻塞条件
         lock = new ReentrantLock(fair);
         notEmpty = lock.newCondition();
         notFull =  lock.newCondition();
     }
 /**
      * Inserts the specified element at the tail of this queue, waiting
      * for space to become available if the queue is full.
      *
      * @throws InterruptedException {@inheritDoc}
      * @throws NullPointerException {@inheritDoc}
      */
     public void put(E e) throws InterruptedException {
         checkNotNull(e);
         final ReentrantLock lock = this.lock;           //lockInterruptibly()允许在等待时由其他线程的Thread.interrupt()方法来中断等待线程而直接返回,这时是不用获取锁的,而会抛出一个InterruptException。           //而ReentrantLock.lock()方法则不允许Thread.interrupt()中断,即使检测到了Thread.interruptted一样会继续尝试获取锁,失败则继续休眠。只是在最后获取锁成功之后在把当前线程置为interrupted状态。
         lock.lockInterruptibly();
         try {               //当队列满时,阻塞插入队列的线程
             while (count == items.length)
                 notFull.await();               //对列不满就入队列
             enqueue(e);
         } finally {               //最后必须释放锁资源
             lock.unlock();
         }
     }
 public E take() throws InterruptedException {
         final ReentrantLock lock = this.lock;           //加锁保证只有一个线程进入take方法
         lock.lockInterruptibly();
         try {               //当队列为空时,阻塞取出元素的线程
             while (count == 0)
                 notEmpty.await();               //当队列队列非空时,允许元素加入队列
             return dequeue();
         } finally {
             lock.unlock();
         }
     }
 /**
      * Inserts element at current put position, advances, and signals.
      * Call only when holding lock.
      */
     private void enqueue(E x) {
         // assert lock.getHoldCount() == 1;
         // assert items[putIndex] == null;
         final Object[] items = this.items;  //确保所有元素只放进同一个数组中
         items[putIndex] = x;
         if (++putIndex == items.length)  //当索引等于数组最大值时,索引置0
             putIndex = 0;
         count++;
         notEmpty.signal();  //使用条件对象notEmpty通知,当调用take,poll,remove时,线程被阻塞,对列为空,当调用enqueue时,队列不为空了,使用signal函数进行通知
     }
 /**
      * Extracts element at current take position, advances, and signals.
      * Call only when holding lock.
      */
     private E dequeue() {
         // assert lock.getHoldCount() == 1;
         // assert items[takeIndex] != null;
         final Object[] items = this.items;
         @SuppressWarnings("unchecked")
         E x = (E) items[takeIndex];
         items[takeIndex] = null;
         if (++takeIndex == items.length)
             takeIndex = 0;
         count--;
         if (itrs != null)
             itrs.elementDequeued();
         notFull.signal();
         return x;
     }

该博客更详细,向博主学习,以后更深入学习后再来完善这篇博客。http://blog.csdn.net/x_i_y_u_e/article/details/52513038

Java源码之阻塞队列的更多相关文章

  1. 【Java源码】集合类-队列Queue

    一.描述 队列Queue这种数据结构,通常指先进先出(FIFO)这种容器.可以模拟生活中依次排队这种场景. 下面是集合体系继承树: 二.Queue Queue和List一样都是Collection的子 ...

  2. Java并发编程:阻塞队列(转载)

    Java并发编程:阻塞队列 在前面几篇文章中,我们讨论了同步容器(Hashtable.Vector),也讨论了并发容器(ConcurrentHashMap.CopyOnWriteArrayList), ...

  3. 12、Java并发编程:阻塞队列

    Java并发编程:阻塞队列 在前面几篇文章中,我们讨论了同步容器(Hashtable.Vector),也讨论了并发容器(ConcurrentHashMap.CopyOnWriteArrayList), ...

  4. (转)Java并发编程:阻塞队列

    Java并发编程:阻塞队列 在前面几篇文章中,我们讨论了同步容器(Hashtable.Vector),也讨论了并发容器(ConcurrentHashMap.CopyOnWriteArrayList), ...

  5. 用Java如何设计一个阻塞队列,然后说说ArrayBlockingQueue和LinkedBlockingQueue

    前言 用Java如何设计一个阻塞队列,这个问题是在面滴滴的时候被问到的.当时确实没回答好,只是说了用个List,然后消费者再用个死循环一直去监控list的是否有值,有值的话就处理List里面的内容.回 ...

  6. 【转】Java并发编程:阻塞队列

    在前面几篇文章中,我们讨论了同步容器(Hashtable.Vector),也讨论了并发容器(ConcurrentHashMap.CopyOnWriteArrayList),这些工具都为我们编写多线程程 ...

  7. Java源码系列1——ArrayList

    本文简单介绍了 ArrayList,并对扩容,添加,删除操作的源代码做分析.能力有限,欢迎指正. ArrayList是什么? ArrayList 就是数组列表,主要用来装载数据.底层实现是数组 Obj ...

  8. 【笔记0-开篇】面试官系统精讲Java源码及大厂真题

    背景 开始阅读 Java 源码的契机,还是在第一年换工作的时候,被大厂的技术面虐的体无完肤,后来总结大厂的面试套路,发现很喜欢问 Java 底层实现,即 Java 源码,于是我花了半年时间,啃下了 J ...

  9. [源码解析] 消息队列 Kombu 之 基本架构

    [源码解析] 消息队列 Kombu 之 基本架构 目录 [源码解析] 消息队列 Kombu 之 基本架构 0x00 摘要 0x01 AMQP 1.1 基本概念 1.2 工作过程 0x02 Poll系列 ...

随机推荐

  1. Spring MVC源码(二) ----- DispatcherServlet 请求处理流程 面试必问

    前端控制器 前端控制器,即所谓的Front Controller,体现的是设计模式中的前端控制器模式.前端控制器处理所有从用户过来的请求.所有用户的请求都要通过前端控制器.SpringMVC框架和其他 ...

  2. 20131201-插件-XML-第十二天(未完)

    以后再写代码的时候,先从中间层|接口|协议开始入手. 在写XML时注意的事情: 在EditPlus中,Tab是缩进 在头文件中的编码格式是"utf-8"是,在Editplus中保存 ...

  3. 【NOIP2017】图书管理员-C++

    描述 图书馆中每本书都有一个图书编码,可以用于快速检索图书,这个图书编码是一个 正整数. 每位借书的读者手中有一个需求码,这个需求码也是一个正整数.如果一本书的图 书编码恰好以读者的需求码结尾,那么这 ...

  4. 使用C#调试Windows服务模板项目

    Windows服务是非常强大的应用程序,可用于在backgorund中执行许多不同类型的任务.他们可以在不需要任何用户登录的情况下启动,并且可以使用除登录用户之外的其他用户帐户运行.但是,如果通过遵循 ...

  5. Android调用系统分享功能总结

    Android分享-调用系统自带的分享功能 实现分享功能的几个办法 1.调用系统的分享功能 2.通过第三方SDK,如ShareSDK,友盟等 3.自行使用各自平台的SDK,比如QQ,微信,微博各自的S ...

  6. android异常 More than one file was found with OS independent path 'META-INF/XXX'

    android 异常总结:一个文件在jar包中出现多次. Error:Execution failed for task ':app:transformResourcesWithMergeJavaRe ...

  7. HashMap源码__tableSizeFor方法解析

    tableSizeFor(int cap)方法返回不小于指定参数cap的最小2的整数次幂,具体是怎么实现的呢?看源码! /** * Returns a power of two size for th ...

  8. tar 命令详解(持续更新)

    可以用man tar查看tar命令使用的权威解释 Main operation mode: -c: 建立压缩档案 -r:向压缩归档文件末尾追加文件 -t:查看内容 -u:更新原压缩包中的文件 -x:解 ...

  9. to_string()函数(C++)

    to_string函数,这是C++11新增的,使用非常方便,简单查了下:C++11标准增加了全局函数std::to_string 函数原型:string to_string (int val);str ...

  10. Jquery 小结

    1. 名词解释 实例对象:var p1=new Person();  p1就是实例对象 构造:function Person(){} 原型对象:在 JavaScript 中,每当定义一个对象(函数也是 ...