AbstractQueuedSynchronizer理解之二(CountDownLatch)

本文分析一下CountDownLatch是如何運用AQS的node

CountDownLatch是什麼

CountDownLatch顧名思義它是一個Latch(門閂),它是用一個計數器實現的,初始狀態計數器的數值等於線程數,每當有線程完成任務後,計數器就會減一。當state爲0時,鎖就會被釋放,凡是以前因搶佔鎖而等待的線程這時候就會被喚醒繼續搶佔鎖。app

CountDownLatch小栗子

public static void main(String[] args) throws InterruptedException{
    int threadSize = 3;
    CountDownLatch doneSignal = new CountDownLatch(threadSize);

    for (int i = 1; i <= threadSize; i++) {
        final int threadNum = i;
        new Thread(() -> {
            System.out.println("thread" + threadNum + ":start");

            try {
                Thread.sleep(1000 * threadNum);
            } catch (InterruptedException e) {
                System.out.println("thread" + threadNum + ":exception");
            }

            doneSignal.countDown();
            System.out.println("thread" + threadNum + ":complete");
        }).start();
    }

    System.out.println("main thread:await");
    doneSignal.await();
    System.out.println("main thread:go on");
}

例子中主線程啓動了三條子線程,睡眠一段時間,此時主線程在等待全部子線程結束後纔會繼續執行下去;
看一下輸出結果:函數

main thread:await
thread1:start
thread2:start
thread3:start
thread1:complete
thread2:complete
thread3:complete
main thread:go on

Process finished with exit code 0

CountDownLatch原理分析

既然CountDownLatch也是AQS的一種使用方式,咱們看一下它的內部類Syc是怎麼實現AQS的:oop

private static final class Sync extends AbstractQueuedSynchronizer {
    private static final long serialVersionUID = 4982264981922014374L;
    
    //構造函數,初始化同步狀態state的值,即線程個數
    Sync(int count) {
        setState(count);
    }

    int getCount() {
        return getState();
    }

    //這裏重寫了方法,在共享模式下,告訴調用者是否能夠搶佔state鎖了,正數表明能夠,負數表明否認;當state爲0時返回正數
    protected int tryAcquireShared(int acquires) {
        return (getState() == 0) ? 1 : -1;
    }

    //共享模式下釋放鎖
    protected boolean tryReleaseShared(int releases) {
        // Decrement count; signal when transition to zero
        for (;;) {
            int c = getState();
            //state爲0時說明沒有什麼可釋放
            if (c == 0)
                return false;
            int nextc = c-1;
            if (compareAndSetState(c, nextc))
                //CAS對state操做成功後返回state值是否爲0,爲0則釋放成功
                return nextc == 0;
        }
    }
}

看完了重寫的AQS同步器後,咱們瞭解了CountDownLatch對state鎖的描述。接下來先看主線程調用的await方法,在await方法裏調用了AQS的acquireSharedInterruptibly:ui

//在共享模式下嘗試搶佔鎖
public final void acquireSharedInterruptibly(int arg)
        throws InterruptedException {
    //線程中斷拋出異常
    if (Thread.interrupted())
        throw new InterruptedException();
    //嘗試搶佔前先查詢一下是否能夠搶佔,若是返回值大於0程序往下執行,小於0則等待
    if (tryAcquireShared(arg) < 0)
        doAcquireSharedInterruptibly(arg);
}


private void doAcquireSharedInterruptibly(int arg)
    throws InterruptedException {
    //在Reentrant解析中咱們看過,往隊列中新增node(共享模式)
    final Node node = addWaiter(Node.SHARED);
    boolean failed = true;
    try {
        for (;;) {
            final Node p = node.predecessor();
            if (p == head) {
                //若是當前node的前繼時head,立刻嘗試搶佔鎖
                int r = tryAcquireShared(arg);
                if (r >= 0) {
                    //若是state==0即容許往下執行,從新設置head並往下傳播信號
                    setHeadAndPropagate(node, r);
                    p.next = null; // help GC
                    failed = false;
                    //獲得往下執行的容許
                    return;
                }
            }
            //如下都跟Reentrant同樣
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                throw new InterruptedException();
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

private void setHeadAndPropagate(Node node, int propagate) {
    Node h = head; // Record old head for check below
    //將當前node設置爲head,清空node的thread、prev
    setHead(node);
    /*
     * Try to signal next queued node if:
     *   Propagation was indicated by caller,
     *     or was recorded (as h.waitStatus either before
     *     or after setHead) by a previous operation
     *     (note: this uses sign-check of waitStatus because
     *      PROPAGATE status may transition to SIGNAL.)
     * and
     *   The next node is waiting in shared mode,
     *     or we don't know, because it appears null
     *
     * The conservatism in both of these checks may cause
     * unnecessary wake-ups, but only when there are multiple
     * racing acquires/releases, so most need signals now or soon
     * anyway.
     */
    //若是propagate大於0,或者原來head的等待狀態小於0或者如今head的等待狀態小於0
    if (propagate > 0 || h == null || h.waitStatus < 0 ||
        (h = head) == null || h.waitStatus < 0) {
        Node s = node.next;
        //準備喚醒下一個節點
        if (s == null || s.isShared())
            doReleaseShared();
    }
}

private void doReleaseShared() {
    /*
     * Ensure that a release propagates, even if there are other
     * in-progress acquires/releases.  This proceeds in the usual
     * way of trying to unparkSuccessor of head if it needs
     * signal. But if it does not, status is set to PROPAGATE to
     * ensure that upon release, propagation continues.
     * Additionally, we must loop in case a new node is added
     * while we are doing this. Also, unlike other uses of
     * unparkSuccessor, we need to know if CAS to reset status
     * fails, if so rechecking.
     */
    for (;;) {
        Node h = head;
        if (h != null && h != tail) {
            int ws = h.waitStatus;
            if (ws == Node.SIGNAL) {
                //若是head的狀態爲SIGNAL,更改狀態爲0
                if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                    continue;            // loop to recheck cases
                //喚醒後繼節點
                unparkSuccessor(h);
            }
            //若是head狀態爲0,更改狀態爲PROPAGATE
            else if (ws == 0 &&
                     !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                continue;                // loop on failed CAS
        }
        //若是head沒有改變,結束當前loop,若是遇到head被別的線程改變,繼續loop
        if (h == head)                   // loop if head changed
            break;
    }
}

釋放鎖的信號一直向後傳播,直到全部node被喚醒並繼續執行,那第一個信號時什麼時候發起的呢?咱們來看一下CountDownLatch的countDown方法,該方法調用了sync的releaseShared方法:this

public final boolean releaseShared(int arg) {
    if (tryReleaseShared(arg)) {
        //若是同步狀態state爲0時,調用doReleaseShared,在這裏就發出了第一個喚醒全部等待node的信號,而後信號自動日後傳播
        doReleaseShared();
        return true;
    }
    return false;
}

總結

CountDownLatch在調用await的時候判斷state釋放爲0,若是大於0則阻塞當前線程,將當前線程的node添加到隊列中等待;在調用countDown時當遇到state減到0時,發出釋放共享鎖的信號,從頭節點的後記節點開始日後傳遞信號,將隊列等待的線程逐個喚醒並繼續往下執行;
在這裏state跟Reentrant的state獨佔鎖含義不一樣,state的含義是由AQS的子類去描述的。線程

相關文章
相關標籤/搜索