BlockingQueue

BlockingQueue介绍与经常使用方法

 

BlockingQueue是一个阻塞队列。在高并发场景是用得很是多的,在线程池中。若是运行线程数目大于核心线程数目时,也会尝试把新加入的线程放到一个BlockingQueue中去。队列的特性就是先进先出很容易理解,在Java里头它的实现类主要有下图的几种,其中最经常使用到的是ArrayBlockingQueue、LinkedBlockingQueue及SynchronousQueue这三种。html

它主要的方法有java

BlockingQueue的核心方法:
一、放入数据android

  (1) add(object)数组

    队列没满的话,放入成功。不然抛出异常。缓存

 (2)offer(object):安全

    表示若是可能的话,将object加到BlockingQueue里,即若是BlockingQueue能够容纳,则返回true,不然返回false.(本方法不阻塞当前执行方法的线程)
 (3)offer(E o, long timeout, TimeUnit unit)并发

      能够设定等待的时间,若是在指定的时间内,还不能往队列中加入BlockingQueue,则返回失败。
(4)put(object)app

       把object加到BlockingQueue里,若是BlockQueue没有空间,则调用此方法的线程阻塞。直到BlockingQueue里面有空间再继续.
二、获取数据
(1)poll(time)ide

   取走BlockingQueue里排在首位的对象,若不能当即取出,则能够等time参数规定的时间,取不到时返回null;
(2)poll(long timeout, TimeUnit unit)函数

   从BlockingQueue取出一个队首的对象,若是在指定时间内,队列一旦有数据可取,则当即返回队列中的数据。不然知道时间超时尚未数据可取,返回失败。

(3)take()

  取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到BlockingQueue有新的数据被加入; 
(4)drainTo()

   一次性从BlockingQueue获取全部可用的数据对象(还能够指定获取数据的个数),经过该方法,能够提高获取数据效率;不须要屡次分批加锁或释放锁。

ArrayBlockingQueue

 

一个由数组支持的有界阻塞队列。它的本质是一个基于数组的BlockingQueue的实现。
 它的容纳大小是固定的。此队列按 FIFO(先进先出)原则对元素进行排序。
 队列的头部 是在队列中存在时间最长的元素。队列的尾部 是在队列中存在时间最短的元素。
 新元素插入到队列的尾部,队列检索操做则是从队列头部开始得到元素。 
 这是一个典型的“有界缓存区”,固定大小的数组在其中保持生产者插入的元素和使用者提取的元素。
 一旦建立了这样的缓存区,就不能再增长其容量。
 试图向已满队列中放入元素会致使放入操做受阻塞,直到BlockingQueue里有新的唤空间才会被醒继续操做;

 试图从空队列中检索元素将致使相似阻塞,直到BlocingkQueue进了新货才会被唤醒。 
 此类支持对等待的生产者线程和使用者线程进行排序的可选公平策略。
 默认状况下,不保证是这种排序。然而,经过在构造函数将公平性 (fairness) 设置为 true 而构造的队列容许按照 FIFO 顺序访问线程。
 公平性一般会下降吞吐量,但也减小了可变性和避免了“不平衡性”。 
 此类及其迭代器实现了 Collection 和 Iterator 接口的全部可选 方法。
 注意1:它是有界阻塞队列。它是数组实现的,是一个典型的“有界缓存区”。数组大小在构造函数指定,并且今后之后不可改变。
 注意2:是它线程安全的,是阻塞的,具体参考BlockingQueue的“注意4”。
 注意3:不接受 null 元素
 注意4:公平性 (fairness)能够在构造函数中指定。

Public Constructors
  ArrayBlockingQueue(int capacity)

Creates an ArrayBlockingQueue with the given (fixed) capacity and default access policy.

  ArrayBlockingQueue(int capacity, boolean fair)

Creates an ArrayBlockingQueue with the given (fixed) capacity and the specified access policy.

  ArrayBlockingQueue(int capacity, boolean fair, Collection<? extends E> c)

Creates an ArrayBlockingQueue with the given (fixed) capacity, the specified access policy and initially containing the elements of the given collection, added in traversal order of the collection's iterator.

 若是为true,则按照 FIFO 顺序访问插入或移除时受阻塞线程的队列;若是为 false,则访问顺序是不肯定的。
  注意5:它实现了BlockingQueue接口。
  注意6:此类及其迭代器实现了 Collection 和 Iterator 接口的全部可选 方法。
  注意7:其容量在构造函数中指定。容量不能够自动扩展,也没提供手动扩展的接口。

 

  注意8:在JDK5/6中,LinkedBlockingQueue和ArrayBlocingQueue等对象的poll(long timeout, TimeUnit unit)存在内存泄露
   Leak的对象是AbstractQueuedSynchronizer.Node,
   据称JDK5会在Update12里Fix,JDK6会在Update2里Fix。

源码分析:

    一个基本数组的阻塞队列。能够设置列队的大小。

它的基本原理实际仍是数组,只不过存、取、删时都要作队列是否满或空的判断。而后加锁访问。

 

[java] view plain copy

  在CODE上查看代码片派生到个人代码片

  1. package java.util.concurrent;  
  2. import java.util.concurrent.locks.Condition;  
  3. import java.util.concurrent.locks.ReentrantLock;  
  4. import java.util.AbstractQueue;  
  5. import java.util.Collection;  
  6. import java.util.Iterator;  
  7. import java.util.NoSuchElementException;  
  8. import java.lang.ref.WeakReference;  
  9. import java.util.Spliterators;  
  10. import java.util.Spliterator;  
  11.   
  12.   
  13. public class ArrayBlockingQueue<E> extends AbstractQueue<E>  
  14.         implements BlockingQueue<E>, java.io.Serializable {  
  15.   
  16.     private static final long serialVersionUID = -817911632652898426L;  
  17.   
  18.     /** 真正存入数据的数组*/  
  19.     final Object[] items;  
  20.   
  21.     /** take, poll, peek or remove的下一个索引 */  
  22.     int takeIndex;  
  23.   
  24.     /** put, offer, or add的下一个索引 */  
  25.     int putIndex;  
  26.   
  27.     /**队列中元素个数*/  
  28.     int count;  
  29.   
  30.   
  31.     /**可重入锁 */  
  32.     final ReentrantLock lock;  
  33.   
  34.     /** 队列不为空的条件 */  
  35.     private final Condition notEmpty;  
  36.   
  37.     /** 队列未满的条件 */  
  38.     private final Condition notFull;  
  39.   
  40.     transient Itrs itrs = null;  
  41.   
  42.   
  43.     /** 
  44.      *当前元素个数-1 
  45.      */  
  46.     final int dec(int i) {  
  47.         return ((i == 0) ? items.length : i) - 1;  
  48.     }  
  49.   
  50.     /** 
  51.      * 返回对应索引上的元素 
  52.      */  
  53.     @SuppressWarnings("unchecked")  
  54.     final E itemAt(int i) {  
  55.         return (E) items[i];  
  56.     }  
  57.   
  58.     /** 
  59.      * 非空检查 
  60.      * 
  61.      * @param v the element 
  62.      */  
  63.     private static void checkNotNull(Object v) {  
  64.         if (v == null)  
  65.             throw new NullPointerException();  
  66.     }  
  67.   
  68.     /** 
  69.      * 元素放入队列,注意调用这个方法时都要先加锁 
  70.      *  
  71.      */  
  72.     private void enqueue(E x) {  
  73.         final Object[] items = this.items;  
  74.         items[putIndex] = x;  
  75.         if (++putIndex == items.length)  
  76.             putIndex = 0;  
  77.         count++;//当前拥有元素个数加1  
  78.         notEmpty.signal();//有一个元素加入成功,那确定队列不为空  
  79.     }  
  80.   
  81.     /** 
  82.      * 元素出队,注意调用这个方法时都要先加锁 
  83.      *  
  84.      */  
  85.     private E dequeue() {  
  86.         final Object[] items = this.items;  
  87.         @SuppressWarnings("unchecked")  
  88.         E x = (E) items[takeIndex];  
  89.         items[takeIndex] = null;  
  90.         if (++takeIndex == items.length)  
  91.             takeIndex = 0;  
  92.         count--;/当前拥有元素个数减1  
  93.         if (itrs != null)  
  94.             itrs.elementDequeued();  
  95.         notFull.signal();//有一个元素取出成功,那确定队列不满  
  96.         return x;  
  97.     }  
  98.   
  99.     /** 
  100.      * 指定删除索引上的元素 
  101.      *  
  102.      */  
  103.     void removeAt(final int removeIndex) {  
  104.         final Object[] items = this.items;  
  105.         if (removeIndex == takeIndex) {  
  106.             items[takeIndex] = null;  
  107.             if (++takeIndex == items.length)  
  108.                 takeIndex = 0;  
  109.             count--;  
  110.             if (itrs != null)  
  111.                 itrs.elementDequeued();  
  112.         } else {  
  113.             final int putIndex = this.putIndex;  
  114.             for (int i = removeIndex;;) {  
  115.                 int next = i + 1;  
  116.                 if (next == items.length)  
  117.                     next = 0;  
  118.                 if (next != putIndex) {  
  119.                     items[i] = items[next];  
  120.                     i = next;  
  121.                 } else {  
  122.                     items[i] = null;  
  123.                     this.putIndex = i;  
  124.                     break;  
  125.                 }  
  126.             }  
  127.             count--;  
  128.             if (itrs != null)  
  129.                 itrs.removedAt(removeIndex);  
  130.         }  
  131.         notFull.signal();//有一个元素删除成功,那确定队列不满  
  132.     }  
  133.   
  134.     /** 
  135.      *  
  136.      * 构造函数,设置队列的初始容量 
  137.      */  
  138.     public ArrayBlockingQueue(int capacity) {  
  139.         this(capacity, false);  
  140.     }  
  141.   
  142.     /** 
  143.      * 构造函数。capacity设置数组大小 ,fair设置是否为公平锁 
  144.      * capacity and the specified access policy. 
  145.      */  
  146.     public ArrayBlockingQueue(int capacity, boolean fair) {  
  147.         if (capacity <= 0)  
  148.             throw new IllegalArgumentException();  
  149.         this.items = new Object[capacity];  
  150.         lock = new ReentrantLock(fair);//是否为公平锁,若是是的话,那么先到的线程先得到锁对象。  
  151.         //不然,由操做系统调度由哪一个线程得到锁,通常为false,性能会比较高  
  152.         notEmpty = lock.newCondition();  
  153.         notFull =  lock.newCondition();  
  154.     }  
  155.   
  156.     /** 
  157.      *构造函数,带有初始内容的队列 
  158.      */  
  159.     public ArrayBlockingQueue(int capacity, boolean fair,  
  160.                               Collection<? extends E> c) {  
  161.         this(capacity, fair);  
  162.   
  163.         final ReentrantLock lock = this.lock;  
  164.         lock.lock(); //要给数组设置内容,先上锁  
  165.         try {  
  166.             int i = 0;  
  167.             try {  
  168.                 for (E e : c) {  
  169.                     checkNotNull(e);  
  170.                     items[i++] = e;//依次拷贝内容  
  171.                 }  
  172.             } catch (ArrayIndexOutOfBoundsException ex) {  
  173.                 throw new IllegalArgumentException();  
  174.             }  
  175.             count = i;  
  176.             putIndex = (i == capacity) ? 0 : i;//若是putIndex大于数组大小 ,那么从0从新开始  
  177.         } finally {  
  178.             lock.unlock();//最后必定要释放锁  
  179.         }  
  180.     }  
  181.   
  182.     /** 
  183.      * 添加一个元素,其实super.add里面调用了offer方法 
  184.      */  
  185.     public boolean add(E e) {  
  186.         return super.add(e);  
  187.     }  
  188.   
  189.     /** 
  190.      *加入成功返回true,不然返回false 
  191.      *  
  192.      */  
  193.     public boolean offer(E e) {  
  194.         checkNotNull(e);  
  195.         final ReentrantLock lock = this.lock;  
  196.         lock.lock();//上锁  
  197.         try {  
  198.             if (count == items.length) //超过数组的容量  
  199.                 return false;  
  200.             else {  
  201.                 enqueue(e); //放入元素  
  202.                 return true;  
  203.             }  
  204.         } finally {  
  205.             lock.unlock();  
  206.         }  
  207.     }  
  208.   
  209.     /** 
  210.      * 若是队列已满的话,就会等待 
  211.      */  
  212.     public void put(E e) throws InterruptedException {  
  213.         checkNotNull(e);  
  214.         final ReentrantLock lock = this.lock;  
  215.         lock.lockInterruptibly();//和lock()方法的区别是让它在阻塞时也可抛出异常跳出  
  216.         try {  
  217.             while (count == items.length)  
  218.                 notFull.await(); //这里就是阻塞了,要注意。若是运行到这里,那么它会释放上面的锁,一直等到notify  
  219.             enqueue(e);  
  220.         } finally {  
  221.             lock.unlock();  
  222.         }  
  223.     }  
  224.   
  225.     /** 
  226.      * 带有超时时间的插入方法,unit表示是按秒、分、时哪种 
  227.      */  
  228.     public boolean offer(E e, long timeout, TimeUnit unit)  
  229.         throws InterruptedException {  
  230.   
  231.         checkNotNull(e);  
  232.         long nanos = unit.toNanos(timeout);  
  233.         final ReentrantLock lock = this.lock;  
  234.         lock.lockInterruptibly();  
  235.         try {  
  236.             while (count == items.length) {  
  237.                 if (nanos <= 0)  
  238.                     return false;  
  239.                 nanos = notFull.awaitNanos(nanos);//带有超时等待的阻塞方法  
  240.             }  
  241.             enqueue(e);//入队  
  242.             return true;  
  243.         } finally {  
  244.             lock.unlock();  
  245.         }  
  246.     }  
  247.   
  248.     //实现的方法,若是当前队列为空,返回null  
  249.     public E poll() {  
  250.         final ReentrantLock lock = this.lock;  
  251.         lock.lock();  
  252.         try {  
  253.             return (count == 0) ? null : dequeue();  
  254.         } finally {  
  255.             lock.unlock();  
  256.         }  
  257.     }  
  258.      //实现的方法,若是当前队列为空,一直阻塞  
  259.     public E take() throws InterruptedException {  
  260.         final ReentrantLock lock = this.lock;  
  261.         lock.lockInterruptibly();  
  262.         try {  
  263.             while (count == 0)  
  264.                 notEmpty.await();//队列为空,阻塞方法  
  265.             return dequeue();  
  266.         } finally {  
  267.             lock.unlock();  
  268.         }  
  269.     }  
  270.     //带有超时时间的取元素方法,不然返回Null  
  271.     public E poll(long timeout, TimeUnit unit) throws InterruptedException {  
  272.         long nanos = unit.toNanos(timeout);  
  273.         final ReentrantLock lock = this.lock;  
  274.         lock.lockInterruptibly();  
  275.         try {  
  276.             while (count == 0) {  
  277.                 if (nanos <= 0)  
  278.                     return null;  
  279.                 nanos = notEmpty.awaitNanos(nanos);//超时等待  
  280.             }  
  281.             return dequeue();//取得元素  
  282.         } finally {  
  283.             lock.unlock();  
  284.         }  
  285.     }  
  286.     //只是看一个队列最前面的元素,取出是不删除队列中的原来元素。队列为空时返回null  
  287.     public E peek() {  
  288.         final ReentrantLock lock = this.lock;  
  289.         lock.lock();  
  290.         try {  
  291.             return itemAt(takeIndex); // 队列为空时返回null  
  292.         } finally {  
  293.             lock.unlock();  
  294.         }  
  295.     }  
  296.   
  297.     /** 
  298.      * 返回队列当前元素个数 
  299.      * 
  300.      */  
  301.     public int size() {  
  302.         final ReentrantLock lock = this.lock;  
  303.         lock.lock();  
  304.         try {  
  305.             return count;  
  306.         } finally {  
  307.             lock.unlock();  
  308.         }  
  309.     }  
  310.   
  311.     /** 
  312.      * 返回当前队列再放入多少个元素就满队 
  313.      */  
  314.     public int remainingCapacity() {  
  315.         final ReentrantLock lock = this.lock;  
  316.         lock.lock();  
  317.         try {  
  318.             return items.length - count;  
  319.         } finally {  
  320.             lock.unlock();  
  321.         }  
  322.     }  
  323.   
  324.     /** 
  325.      *  从队列中删除一个元素的方法。删除成功返回true,不然返回false 
  326.      */  
  327.     public boolean remove(Object o) {  
  328.         if (o == null) return false;  
  329.         final Object[] items = this.items;  
  330.         final ReentrantLock lock = this.lock;  
  331.         lock.lock();  
  332.         try {  
  333.             if (count > 0) {  
  334.                 final int putIndex = this.putIndex;  
  335.                 int i = takeIndex;  
  336.                 do {  
  337.                     if (o.equals(items[i])) {  
  338.                         removeAt(i); //真正删除的方法  
  339.                         return true;  
  340.                     }  
  341.                     if (++i == items.length)  
  342.                         i = 0;  
  343.                 } while (i != putIndex);//一直不断的循环取出来作判断  
  344.             }  
  345.             return false;  
  346.         } finally {  
  347.             lock.unlock();  
  348.         }  
  349.     }  
  350.   
  351.     /** 
  352.      * 是否包含一个元素 
  353.      */  
  354.     public boolean contains(Object o) {  
  355.         if (o == null) return false;  
  356.         final Object[] items = this.items;  
  357.         final ReentrantLock lock = this.lock;  
  358.         lock.lock();  
  359.         try {  
  360.             if (count > 0) {  
  361.                 final int putIndex = this.putIndex;  
  362.                 int i = takeIndex;  
  363.                 do {  
  364.                     if (o.equals(items[i]))  
  365.                         return true;  
  366.                     if (++i == items.length)  
  367.                         i = 0;  
  368.                 } while (i != putIndex);  
  369.             }  
  370.             return false;  
  371.         } finally {  
  372.             lock.unlock();  
  373.         }  
  374.     }  
  375.   
  376.     /** 
  377.      * 清空队列 
  378.      * 
  379.      */  
  380.     public void clear() {  
  381.         final Object[] items = this.items;  
  382.         final ReentrantLock lock = this.lock;  
  383.         lock.lock();  
  384.         try {  
  385.             int k = count;  
  386.             if (k > 0) {  
  387.                 final int putIndex = this.putIndex;  
  388.                 int i = takeIndex;  
  389.                 do {  
  390.                     items[i] = null;  
  391.                     if (++i == items.length)  
  392.                         i = 0;  
  393.                 } while (i != putIndex);  
  394.                 takeIndex = putIndex;  
  395.                 count = 0;  
  396.                 if (itrs != null)  
  397.                     itrs.queueIsEmpty();  
  398.                 for (; k > 0 && lock.hasWaiters(notFull); k--)  
  399.                     notFull.signal();  
  400.             }  
  401.         } finally {  
  402.             lock.unlock();  
  403.         }  
  404.     }  
  405.   
  406.     /** 
  407.      * 取出全部元素到集合 
  408.      */  
  409.     public int drainTo(Collection<? super E> c) {  
  410.         return drainTo(c, Integer.MAX_VALUE);  
  411.     }  
  412.   
  413.     /** 
  414.      * 取出全部元素到集合 
  415.      */  
  416.     public int drainTo(Collection<? super E> c, int maxElements) {  
  417.         checkNotNull(c);  
  418.         if (c == this)  
  419.             throw new IllegalArgumentException();  
  420.         if (maxElements <= 0)  
  421.             return 0;  
  422.         final Object[] items = this.items;  
  423.         final ReentrantLock lock = this.lock;  
  424.         lock.lock();  
  425.         try {  
  426.             int n = Math.min(maxElements, count);  
  427.             int take = takeIndex;  
  428.             int i = 0;  
  429.             try {  
  430.                 while (i < n) {  
  431.                     @SuppressWarnings("unchecked")  
  432.                     E x = (E) items[take];  
  433.                     c.add(x);  
  434.                     items[take] = null;  
  435.                     if (++take == items.length)  
  436.                         take = 0;  
  437.                     i++;  
  438.                 }  
  439.                 return n;  
  440.             } finally {  
  441.                 // Restore invariants even if c.add() threw  
  442.                 if (i > 0) {  
  443.                     count -= i;  
  444.                     takeIndex = take;  
  445.                     if (itrs != null) {  
  446.                         if (count == 0)  
  447.                             itrs.queueIsEmpty();  
  448.                         else if (i > take)  
  449.                             itrs.takeIndexWrapped();  
  450.                     }  
  451.                     for (; i > 0 && lock.hasWaiters(notFull); i--)  
  452.                         notFull.signal();  
  453.                 }  
  454.             }  
  455.         } finally {  
  456.             lock.unlock();  
  457.         }  
  458.     }  
  459.   
  460.   
  461. }  

 

使用实例:

生产者-消费者模型

 

    大量的实现ArrayBlockingQueue已经作掉了,包括判空,线程挂起等操做都封装在ArrayBlockingQueue中。生产者只须要关心生产,消费者只须要关心消费。而若是不使用ArrayBlockingQueue的话,具体的生产者还须要去通知消费者,还须要关心整个容器是否满了。从这里能够看出ArrayBlockingQueue是一种比较好的实现方式,高度的内聚。

 

Producer.java

[java] view plain copy

  1.  
  2. public class Producer implements Runnable{  
  3.       
  4.     //容器  
  5.     private final ArrayBlockingQueue<Bread> queue;  
  6.       
  7.     public Producer(ArrayBlockingQueue<Bread> queue){  
  8.         this.queue = queue;  
  9.     }  
  10.   
  11.     /* (non-Javadoc) 
  12.      * @see java.lang.Runnable#run() 
  13.      */  
  14.     @Override  
  15.     public void run() {  
  16.         while(true){  
  17.             produce();  
  18.         }  
  19.     }  
  20.       
  21.     public void produce(){  
  22.         /** 
  23.          * put()方法是若是容器满了的话就会把当前线程挂起 
  24.          * offer()方法是容器若是满的话就会返回false。 
  25.          */  
  26.         try {  
  27.             Bread bread = new Bread();  
  28.             queue.put(bread);  
  29.             System.out.println("Producer:"+bread);  
  30.         } catch (InterruptedException e) {  
  31.             e.printStackTrace();  
  32.         }  
  33.     }  
  34. }  

 

Consumer.java

[java] view plain copy

  1.  
  2. public class Consumer implements Runnable{  
  3.       
  4.     //容器  
  5.     private final ArrayBlockingQueue<Bread> queue;  
  6.       
  7.     public Consumer(ArrayBlockingQueue<Bread> queue){  
  8.         this.queue = queue;  
  9.     }  
  10.   
  11.     /* (non-Javadoc) 
  12.      * @see java.lang.Runnable#run() 
  13.      */  
  14.     @Override  
  15.     public void run() {  
  16.         while(true){  
  17.             consume();  
  18.         }  
  19.     }  
  20.       
  21.     public void consume(){  
  22.         /** 
  23.          * take()方法和put()方法是对应的,从中拿一个数据,若是拿不到线程挂起 
  24.          * poll()方法和offer()方法是对应的,从中拿一个数据,若是没有直接返回null 
  25.          */  
  26.         try {  
  27.             Bread bread = queue.take();  
  28.             System.out.println("consumer:"+bread);  
  29.         } catch (InterruptedException e) {  
  30.             e.printStackTrace();  
  31.         }  
  32.     }  
  33. }  

 

Client.java

 

[java] view plain copy

  1.  
  2. public class Client {  
  3.   
  4.     /** 
  5.      * @param args 
  6.      */  
  7.     public static void main(String[] args) {  
  8.         int capacity = 10;  
  9.         ArrayBlockingQueue<Bread> queue = new ArrayBlockingQueue<Bread>(capacity);  
  10.   
  11.         new Thread(new Producer(queue)).start();  
  12.         new Thread(new Producer(queue)).start();  
  13.         new Thread(new Consumer(queue)).start();  
  14.         new Thread(new Consumer(queue)).start();  
  15.         new Thread(new Consumer(queue)).start();  
  16.     }  
  17.   
  18. }  

 

 

 

参考:http://blog.csdn.net/evankaka/article/details/51706109

http://blog.csdn.net/hudashi/article/details/7076745

相关文章
相关标签/搜索