通過ArrayBlockingQueue源碼簡析一個AQS和多個Condition工作機制

在學習ReentrantLock時會不會有這樣的問題,爲併發包中的Lock啥要支持多個等待隊列?

爲啥ArrayBlockingQueue是一個鎖,兩個Condition?

ReentrantLock裏的sync變量(FairSync、NonfairSync都是繼承了Sync,Sync繼承了AbstractQueuedSynchronizer),AbstractQueuedSynchronizer的內部類ConditionObject實現了Condition接口

 public class ConditionObject implements Condition, java.io.Serializable {
        private static final long serialVersionUID = 1173984872572414699L;
        /** First node of condition queue. */
        private transient Node firstWaiter;
        /** Last node of condition queue. */
        private transient Node lastWaiter;
......

這裏的ArrayBlockingQueue源碼不是全部的,只是通過主要源碼分析阻塞隊列的消費者-生產者模型機制。 

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

    /** The queued items */
    final Object[] items;
   
    //這裏通過takeIndex、putIndex下標將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;

    /** Main lock guarding all access ,通過lock控制獲取元素、存放元素 */
    final ReentrantLock lock;

    /** Condition for waiting takes ,等待獲取元素條件*/
    private final Condition notEmpty;

    /** Condition for waiting puts ,等待存放元素條件*/
    private final Condition notFull;
    
    //從隊列中獲取一個元素
    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            //如果數組中元素個數爲0,則該要從數組中獲取元素的消費者線程阻塞在notEmpty條件上
            while (count == 0)
                notEmpty.await();
            //數組中的元素個數不爲0,則返回獲取元素
            return dequeue();
        } finally {
            lock.unlock();
        }
    }
   /**
     * 提取元素,移動takeIndex下標,喚醒一個生成者線程,將生產的元素放入到數組中
     * Extracts element at current take position, advances, and signals.
     * Call only when holding lock.
     */
    private E dequeue() {
        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;
    }

    //向數組中存放一個生產出來的元素e
    public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            //如果數組已滿,則該生產者線程阻塞在notFull條件上
            while (count == items.length)
                notFull.await();
            //向數組中插入元素
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }
    
    private static void checkNotNull(Object v) {
        if (v == null)
            throw new NullPointerException();
    }
    /**
     * 插入元素,移動putIndex下標,喚醒阻塞在notEmpty上的消費者線程
     * Inserts element at current put position, advances, and signals.
     * Call only when holding lock.
     */
    private void enqueue(E x) {
        final Object[] items = this.items;
        items[putIndex] = x;
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        notEmpty.signal();
    }

消費者線程是等待在notEmpty條件上,生產者是等待在notFull條件上,這樣就比較明確的知道等待在某個條件上的線程的功能是啥,能夠準確的喚醒需要某個功能(如生產元素、消費元素)的線程,讓其繼續工作。

爲啥ArrayBlockingQueue是一個鎖呢?因爲items數組、takeIndex、putIndex、count都是普通變量,線程從條件狀態喚醒後,必須獲得與Condition關聯的鎖,這樣線程進行這些變量的操作都是線程安全的。

    /**
     * Wakes up one waiting thread.
     * 喚醒一個等待在Condition上的線程。該線程從等待方法返回前必須獲得與Condition關聯的鎖
     */
    void signal();

如果使用synchronized來實現阻塞隊列的話,則需要使用兩個對象加鎖,一個鎖對象控制生產、一個鎖對象控制消費;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章