Java併發編程:阻塞隊列

Java併發編程:阻塞隊列html

  在前面幾篇文章中,咱們討論了同步容器(Hashtable、Vector),也討論了併發容器(ConcurrentHashMap、CopyOnWriteArrayList),這些工具都爲咱們編寫多線程程序提供了很大的方便。今天咱們來討論另一類容器:阻塞隊列。java

  在前面咱們接觸的隊列都是非阻塞隊列,好比PriorityQueue、LinkedList(LinkedList是雙向鏈表,它實現了Dequeue接口)。編程

  使用非阻塞隊列的時候有一個很大問題就是:它不會對當前線程產生阻塞,那麼在面對相似消費者-生產者的模型時,就必須額外地實現同步策略以及線程間喚醒策略,這個實現起來就很是麻煩。可是有了阻塞隊列就不同了,它會對當前線程產生阻塞,好比一個線程從一個空的阻塞隊列中取元素,此時線程會被阻塞直到阻塞隊列中有了元素。當隊列中有元素後,被阻塞的線程會自動被喚醒(不須要咱們編寫代碼去喚醒)。這樣提供了極大的方便性。數組

  本文先講述一下java.util.concurrent包下提供主要的幾種阻塞隊列,而後分析了阻塞隊列和非阻塞隊列的中的各個方法,接着分析了阻塞隊列的實現原理,最後給出了一個實際例子和幾個使用場景。多線程

  一.幾種主要的阻塞隊列併發

  二.阻塞隊列中的方法 VS 非阻塞隊列中的方法socket

  三.阻塞隊列的實現原理ide

  四.示例和使用場景工具

  如有不正之處請多多諒解,並歡迎批評指正。this

  請尊重做者勞動成果,轉載請標明原文連接:

   http://www.cnblogs.com/dolphin0520/p/3932906.html

一.幾種主要的阻塞隊列

  自從Java 1.5以後,在java.util.concurrent包下提供了若干個阻塞隊列,主要有如下幾個:

  ArrayBlockingQueue:基於數組實現的一個阻塞隊列,在建立ArrayBlockingQueue對象時必須制定容量大小。而且能夠指定公平性與非公平性,默認狀況下爲非公平的,即不保證等待時間最長的隊列最優先可以訪問隊列。

  LinkedBlockingQueue:基於鏈表實現的一個阻塞隊列,在建立LinkedBlockingQueue對象時若是不指定容量大小,則默認大小爲Integer.MAX_VALUE。

  PriorityBlockingQueue:以上2種隊列都是先進先出隊列,而PriorityBlockingQueue卻不是,它會按照元素的優先級對元素進行排序,按照優先級順序出隊,每次出隊的元素都是優先級最高的元素。注意,此阻塞隊列爲無界阻塞隊列,即容量沒有上限(經過源碼就能夠知道,它沒有容器滿的信號標誌),前面2種都是有界隊列。

  DelayQueue:基於PriorityQueue,一種延時阻塞隊列,DelayQueue中的元素只有當其指定的延遲時間到了,纔可以從隊列中獲取到該元素。DelayQueue也是一個無界隊列,所以往隊列中插入數據的操做(生產者)永遠不會被阻塞,而只有獲取數據的操做(消費者)纔會被阻塞。

二.阻塞隊列中的方法 VS 非阻塞隊列中的方法

1.非阻塞隊列中的幾個主要方法:

  add(E e):將元素e插入到隊列末尾,若是插入成功,則返回true;若是插入失敗(即隊列已滿),則會拋出異常;

  remove():移除隊首元素,若移除成功,則返回true;若是移除失敗(隊列爲空),則會拋出異常;

  offer(E e):將元素e插入到隊列末尾,若是插入成功,則返回true;若是插入失敗(即隊列已滿),則返回false;

  poll():移除並獲取隊首元素,若成功,則返回隊首元素;不然返回null;

  peek():獲取隊首元素,若成功,則返回隊首元素;不然返回null

 

  對於非阻塞隊列,通常狀況下建議使用offer、poll和peek三個方法,不建議使用add和remove方法。由於使用offer、poll和peek三個方法能夠經過返回值判斷操做成功與否,而使用add和remove方法卻不能達到這樣的效果。注意,非阻塞隊列中的方法都沒有進行同步措施。

2.阻塞隊列中的幾個主要方法:

  阻塞隊列包括了非阻塞隊列中的大部分方法,上面列舉的5個方法在阻塞隊列中都存在,可是要注意這5個方法在阻塞隊列中都進行了同步措施。除此以外,阻塞隊列提供了另外4個很是有用的方法:

  put(E e)

  take()

  offer(E e,long timeout, TimeUnit unit)

  poll(long timeout, TimeUnit unit)

  

  put方法用來向隊尾存入元素,若是隊列滿,則等待;

  take方法用來從隊首取元素,若是隊列爲空,則等待;

  offer方法用來向隊尾存入元素,若是隊列滿,則等待必定的時間,當時間期限達到時,若是尚未插入成功,則返回false;不然返回true;

  poll方法用來從隊首取元素,若是隊列空,則等待必定的時間,當時間期限達到時,若是取到,則返回null;不然返回取得的元素;

三.阻塞隊列的實現原理

  前面談到了非阻塞隊列和阻塞隊列中經常使用的方法,下面來探討阻塞隊列的實現原理,本文以ArrayBlockingQueue爲例,其餘阻塞隊列實現原理可能和ArrayBlockingQueue有一些差異,可是大致思路應該相似,有興趣的朋友可自行查看其餘阻塞隊列的實現源碼。

  首先看一下ArrayBlockingQueue類中的幾個成員變量:

public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {

private static final long serialVersionUID = -817911632652898426L;

/** The queued items  */
private final E[] items;
/** items index for next take, poll or remove */
private int takeIndex;
/** items index for next put, offer, or add. */
private int putIndex;
/** Number of items in the queue */
private int count;

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

/** Main lock guarding all access */
private final ReentrantLock lock;
/** Condition for waiting takes */
private final Condition notEmpty;
/** Condition for waiting puts */
private final Condition notFull;
}

   能夠看出,ArrayBlockingQueue中用來存儲元素的其實是一個數組,takeIndex和putIndex分別表示隊首元素和隊尾元素的下標,count表示隊列中元素的個數。

  lock是一個可重入鎖,notEmpty和notFull是等待條件。

  下面看一下ArrayBlockingQueue的構造器,構造器有三個重載版本:

public ArrayBlockingQueue(int capacity) {
}
public ArrayBlockingQueue(int capacity, boolean fair) {

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

   第一個構造器只有一個參數用來指定容量,第二個構造器能夠指定容量和公平性,第三個構造器能夠指定容量、公平性以及用另一個集合進行初始化。

  而後看它的兩個關鍵方法的實現:put()和take():

public void put(E e) throws InterruptedException {
    if (e == null) throw new NullPointerException();
    final E[] items = this.items;
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        try {
            while (count == items.length)
                notFull.await();
        } catch (InterruptedException ie) {
            notFull.signal(); // propagate to non-interrupted thread
            throw ie;
        }
        insert(e);
    } finally {
        lock.unlock();
    }
}

   從put方法的實現能夠看出,它先獲取了鎖,而且獲取的是可中斷鎖,而後判斷當前元素個數是否等於數組的長度,若是相等,則調用notFull.await()進行等待,若是捕獲到中斷異常,則喚醒線程並拋出異常。

  當被其餘線程喚醒時,經過insert(e)方法插入元素,最後解鎖。

  咱們看一下insert方法的實現:

private void insert(E x) {
    items[putIndex] = x;
    putIndex = inc(putIndex);
    ++count;
    notEmpty.signal();
}

   它是一個private方法,插入成功後,經過notEmpty喚醒正在等待取元素的線程。

  下面是take()方法的實現:

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        try {
            while (count == 0)
                notEmpty.await();
        } catch (InterruptedException ie) {
            notEmpty.signal(); // propagate to non-interrupted thread
            throw ie;
        }
        E x = extract();
        return x;
    } finally {
        lock.unlock();
    }
}

   跟put方法實現很相似,只不過put方法等待的是notFull信號,而take方法等待的是notEmpty信號。在take方法中,若是能夠取元素,則經過extract方法取得元素,下面是extract方法的實現:

private E extract() {
    final E[] items = this.items;
    E x = items[takeIndex];
    items[takeIndex] = null;
    takeIndex = inc(takeIndex);
    --count;
    notFull.signal();
    return x;
}

   跟insert方法也很相似。

  其實從這裏你們應該明白了阻塞隊列的實現原理,事實它和咱們用Object.wait()、Object.notify()和非阻塞隊列實現生產者-消費者的思路相似,只不過它把這些工做一塊兒集成到了阻塞隊列中實現。

四.示例和使用場景

  下面先使用Object.wait()和Object.notify()、非阻塞隊列實現生產者-消費者模式:

public class Test {
	private int queueSize = 10;
	private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(queueSize);
	
	public static void main(String[] args)  {
		Test test = new Test();
		Producer producer = test.new Producer();
		Consumer consumer = test.new Consumer();
		
		producer.start();
		consumer.start();
	}
	
	class Consumer extends Thread{
		
		@Override
		public void run() {
			consume();
		}
		
		private void consume() {
			while(true){
				synchronized (queue) {
					while(queue.size() == 0){
						try {
							System.out.println("隊列空,等待數據");
							queue.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
							queue.notify();
						}
					}
					queue.poll();          //每次移走隊首元素
					queue.notify();
					System.out.println("從隊列取走一個元素,隊列剩餘"+queue.size()+"個元素");
				}
			}
		}
	}
	
	class Producer extends Thread{
		
		@Override
		public void run() {
			produce();
		}
		
		private void produce() {
			while(true){
				synchronized (queue) {
					while(queue.size() == queueSize){
						try {
							System.out.println("隊列滿,等待有空餘空間");
							queue.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
							queue.notify();
						}
					}
					queue.offer(1);        //每次插入一個元素
					queue.notify();
					System.out.println("向隊列取中插入一個元素,隊列剩餘空間:"+(queueSize-queue.size()));
				}
			}
		}
	}
}

   這個是經典的生產者-消費者模式,經過阻塞隊列和Object.wait()和Object.notify()實現,wait()和notify()主要用來實現線程間通訊。

  具體的線程間通訊方式(wait和notify的使用)在後續問章中會講述到。

  下面是使用阻塞隊列實現的生產者-消費者模式:

public class Test {
	private int queueSize = 10;
	private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(queueSize);
	
	public static void main(String[] args)  {
		Test test = new Test();
		Producer producer = test.new Producer();
		Consumer consumer = test.new Consumer();
		
		producer.start();
		consumer.start();
	}
	
	class Consumer extends Thread{
		
		@Override
		public void run() {
			consume();
		}
		
		private void consume() {
			while(true){
				try {
					queue.take();
					System.out.println("從隊列取走一個元素,隊列剩餘"+queue.size()+"個元素");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	class Producer extends Thread{
		
		@Override
		public void run() {
			produce();
		}
		
		private void produce() {
			while(true){
				try {
					queue.put(1);
					System.out.println("向隊列取中插入一個元素,隊列剩餘空間:"+(queueSize-queue.size()));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

   有沒有發現,使用阻塞隊列代碼要簡單得多,不須要再單獨考慮同步和線程間通訊的問題。

  在併發編程中,通常推薦使用阻塞隊列,這樣實現能夠儘可能地避免程序出現意外的錯誤。

  阻塞隊列使用最經典的場景就是socket客戶端數據的讀取和解析,讀取數據的線程不斷將數據放入隊列,而後解析線程不斷從隊列取數據解析。還有其餘相似的場景,只要符合生產者-消費者模型的均可以使用阻塞隊列。

  參考資料:

  《Java編程實戰》

  http://ifeve.com/java-blocking-queue/

  http://endual.iteye.com/blog/1412212

  http://blog.csdn.net/zzp_403184692/article/details/8021615

  http://www.cnblogs.com/juepei/p/3922401.html

相關文章
相關標籤/搜索