1. 程式人生 > >12-Java併發程式設計:阻塞佇列

12-Java併發程式設計:阻塞佇列

Java併發程式設計:阻塞佇列

  在前面幾篇文章中,我們討論了同步容器(Hashtable、Vector),也討論了併發容器(ConcurrentHashMap、CopyOnWriteArrayList),這些工具都為我們編寫多執行緒程式提供了很大的方便。今天我們來討論另外一類容器:阻塞佇列。

  在前面我們接觸的佇列都是非阻塞佇列,比如PriorityQueue、LinkedList(LinkedList是雙向連結串列,它實現了Dequeue介面)。

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

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

  一.幾種主要的阻塞佇列

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

  三.阻塞佇列的實現原理

  四.示例和使用場景

一.幾種主要的阻塞佇列

  自從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程式設計實戰》