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

相關文章
相關標籤/搜索