国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

AbstractQueuedSynchronizer理解之二(CountDownLatch)

張憲坤 / 2480人閱讀

摘要:本文分析一下是如何運(yùn)用的是什么顧名思義它是一個門閂,它是用一個計數(shù)器實現(xiàn)的,初始狀態(tài)計數(shù)器的數(shù)值等于線程數(shù),每當(dāng)有線程完成任務(wù)后,計數(shù)器就會減一。當(dāng)為時,鎖就會被釋放,凡是之前因搶占鎖而等待的線程這時候就會被喚醒繼續(xù)搶占鎖。

本文分析一下CountDownLatch是如何運(yùn)用AQS的

CountDownLatch是什么

CountDownLatch顧名思義它是一個Latch(門閂),它是用一個計數(shù)器實現(xiàn)的,初始狀態(tài)計數(shù)器的數(shù)值等于線程數(shù),每當(dāng)有線程完成任務(wù)后,計數(shù)器就會減一。當(dāng)state為0時,鎖就會被釋放,凡是之前因搶占鎖而等待的線程這時候就會被喚醒繼續(xù)搶占鎖。

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");
}

例子中主線程啟動了三條子線程,睡眠一段時間,此時主線程在等待所有子線程結(jié)束后才會繼續(xù)執(zhí)行下去;
看一下輸出結(jié)果:

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的一種使用方式,我們看一下它的內(nèi)部類Syc是怎么實現(xiàn)AQS的:

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

    int getCount() {
        return getState();
    }

    //這里重寫了方法,在共享模式下,告訴調(diào)用者是否可以搶占state鎖了,正數(shù)代表可以,負(fù)數(shù)代表否定;當(dāng)state為0時返回正數(shù)
    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鎖的描述。接下來先看主線程調(diào)用的await方法,在await方法里調(diào)用了AQS的acquireSharedInterruptibly:

//在共享模式下嘗試搶占鎖
public final void acquireSharedInterruptibly(int arg)
        throws InterruptedException {
    //線程中斷拋出異常
    if (Thread.interrupted())
        throw new InterruptedException();
    //嘗試搶占前先查詢一下是否可以搶占,如果返回值大于0程序往下執(zhí)行,小于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) {
                //如果當(dāng)前node的前繼時head,馬上嘗試搶占鎖
                int r = tryAcquireShared(arg);
                if (r >= 0) {
                    //如果state==0即允許往下執(zhí)行,重新設(shè)置head并往下傳播信號
                    setHeadAndPropagate(node, r);
                    p.next = null; // help GC
                    failed = false;
                    //得到往下執(zhí)行的允許
                    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
    //將當(dāng)前node設(shè)置為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的等待狀態(tài)小于0或者現(xiàn)在head的等待狀態(tài)小于0
    if (propagate > 0 || h == null || h.waitStatus < 0 ||
        (h = head) == null || h.waitStatus < 0) {
        Node s = node.next;
        //準(zhǔn)備喚醒下一個節(jié)點(diǎn)
        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的狀態(tài)為SIGNAL,更改狀態(tài)為0
                if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                    continue;            // loop to recheck cases
                //喚醒后繼節(jié)點(diǎn)
                unparkSuccessor(h);
            }
            //如果head狀態(tài)為0,更改狀態(tài)為PROPAGATE
            else if (ws == 0 &&
                     !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                continue;                // loop on failed CAS
        }
        //如果head沒有改變,結(jié)束當(dāng)前l(fā)oop,如果遇到head被別的線程改變,繼續(xù)loop
        if (h == head)                   // loop if head changed
            break;
    }
}

釋放鎖的信號一直向后傳播,直到所有node被喚醒并繼續(xù)執(zhí)行,那第一個信號時何時發(fā)起的呢?我們來看一下CountDownLatch的countDown方法,該方法調(diào)用了sync的releaseShared方法:

public final boolean releaseShared(int arg) {
    if (tryReleaseShared(arg)) {
        //如果同步狀態(tài)state為0時,調(diào)用doReleaseShared,在這里就發(fā)出了第一個喚醒所有等待node的信號,然后信號自動往后傳播
        doReleaseShared();
        return true;
    }
    return false;
}

總結(jié)

CountDownLatch在調(diào)用await的時候判斷state釋放為0,如果大于0則阻塞當(dāng)前線程,將當(dāng)前線程的node添加到隊列中等待;在調(diào)用countDown時當(dāng)遇到state減到0時,發(fā)出釋放共享鎖的信號,從頭節(jié)點(diǎn)的后記節(jié)點(diǎn)開始往后傳遞信號,將隊列等待的線程逐個喚醒并繼續(xù)往下執(zhí)行;
在這里state跟Reentrant的state獨(dú)占鎖含義不同,state的含義是由AQS的子類去描述的。

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/70916.html

相關(guān)文章

  • AbstractQueuedSynchronizer理解之二CountDownLatch

    摘要:本文分析一下是如何運(yùn)用的是什么顧名思義它是一個門閂,它是用一個計數(shù)器實現(xiàn)的,初始狀態(tài)計數(shù)器的數(shù)值等于線程數(shù),每當(dāng)有線程完成任務(wù)后,計數(shù)器就會減一。當(dāng)為時,鎖就會被釋放,凡是之前因搶占鎖而等待的線程這時候就會被喚醒繼續(xù)搶占鎖。 本文分析一下CountDownLatch是如何運(yùn)用AQS的 CountDownLatch是什么 CountDownLatch顧名思義它是一個Latch(門閂),它...

    shery 評論0 收藏0
  • AbstractQueuedSynchronizer理解之二CountDownLatch

    摘要:本文分析一下是如何運(yùn)用的是什么顧名思義它是一個門閂,它是用一個計數(shù)器實現(xiàn)的,初始狀態(tài)計數(shù)器的數(shù)值等于線程數(shù),每當(dāng)有線程完成任務(wù)后,計數(shù)器就會減一。當(dāng)為時,鎖就會被釋放,凡是之前因搶占鎖而等待的線程這時候就會被喚醒繼續(xù)搶占鎖。 本文分析一下CountDownLatch是如何運(yùn)用AQS的 CountDownLatch是什么 CountDownLatch顧名思義它是一個Latch(門閂),它...

    greatwhole 評論0 收藏0
  • AbstractQueuedSynchronizer理解之三(Semaphore)

    摘要:信號可以理解為一種許可,拿到許可的線程才可以繼續(xù)執(zhí)行。的計數(shù)器其實記錄的就是許可的數(shù)量,當(dāng)許可數(shù)量為時,方法就會阻塞。 本文接著分析Semaphore的實現(xiàn)原理 Semaphore是什么 Semaphore是一個計數(shù)信號量。Semaphore(信號)可以理解為一種許可,拿到許可的線程才可以繼續(xù)執(zhí)行。Semaphore的計數(shù)器其實記錄的就是許可的數(shù)量,當(dāng)許可數(shù)量為0時,acquire方法...

    MingjunYang 評論0 收藏0
  • AbstractQueuedSynchronizer理解之三(Semaphore)

    摘要:信號可以理解為一種許可,拿到許可的線程才可以繼續(xù)執(zhí)行。的計數(shù)器其實記錄的就是許可的數(shù)量,當(dāng)許可數(shù)量為時,方法就會阻塞。 本文接著分析Semaphore的實現(xiàn)原理 Semaphore是什么 Semaphore是一個計數(shù)信號量。Semaphore(信號)可以理解為一種許可,拿到許可的線程才可以繼續(xù)執(zhí)行。Semaphore的計數(shù)器其實記錄的就是許可的數(shù)量,當(dāng)許可數(shù)量為0時,acquire方法...

    馬忠志 評論0 收藏0
  • AbstractQueuedSynchronizer理解之三(Semaphore)

    摘要:信號可以理解為一種許可,拿到許可的線程才可以繼續(xù)執(zhí)行。的計數(shù)器其實記錄的就是許可的數(shù)量,當(dāng)許可數(shù)量為時,方法就會阻塞。 本文接著分析Semaphore的實現(xiàn)原理 Semaphore是什么 Semaphore是一個計數(shù)信號量。Semaphore(信號)可以理解為一種許可,拿到許可的線程才可以繼續(xù)執(zhí)行。Semaphore的計數(shù)器其實記錄的就是許可的數(shù)量,當(dāng)許可數(shù)量為0時,acquire方法...

    zollero 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<