摘要:本文分析一下是如何運(yùn)用的是什么顧名思義它是一個(gè)門(mén)閂,它是用一個(gè)計(jì)數(shù)器實(shí)現(xiàn)的,初始狀態(tài)計(jì)數(shù)器的數(shù)值等于線程數(shù),每當(dāng)有線程完成任務(wù)后,計(jì)數(shù)器就會(huì)減一。當(dāng)為時(shí),鎖就會(huì)被釋放,凡是之前因搶占鎖而等待的線程這時(shí)候就會(huì)被喚醒繼續(xù)搶占鎖。
本文分析一下CountDownLatch是如何運(yùn)用AQS的
CountDownLatch是什么CountDownLatch顧名思義它是一個(gè)Latch(門(mén)閂),它是用一個(gè)計(jì)數(shù)器實(shí)現(xiàn)的,初始狀態(tài)計(jì)數(shù)器的數(shù)值等于線程數(shù),每當(dāng)有線程完成任務(wù)后,計(jì)數(shù)器就會(huì)減一。當(dāng)state為0時(shí),鎖就會(huì)被釋放,凡是之前因搶占鎖而等待的線程這時(shí)候就會(huì)被喚醒繼續(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"); }
例子中主線程啟動(dòng)了三條子線程,睡眠一段時(shí)間,此時(shí)主線程在等待所有子線程結(jié)束后才會(huì)繼續(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 0CountDownLatch原理分析
既然CountDownLatch也是AQS的一種使用方式,我們看一下它的內(nèi)部類Syc是怎么實(shí)現(xiàn)AQS的:
private static final class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 4982264981922014374L; //構(gòu)造函數(shù),初始化同步狀態(tài)state的值,即線程個(gè)數(shù) Sync(int count) { setState(count); } int getCount() { return getState(); } //這里重寫(xiě)了方法,在共享模式下,告訴調(diào)用者是否可以搶占state鎖了,正數(shù)代表可以,負(fù)數(shù)代表否定;當(dāng)state為0時(shí)返回正數(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時(shí)說(shuō)明沒(méi)有什么可釋放 if (c == 0) return false; int nextc = c-1; if (compareAndSetState(c, nextc)) //CAS對(duì)state操作成功后返回state值是否為0,為0則釋放成功 return nextc == 0; } } }
看完了重寫(xiě)的AQS同步器后,我們了解了CountDownLatch對(duì)state鎖的描述。接下來(lái)先看主線程調(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解析中我們看過(guò),往隊(duì)列中新增node(共享模式) final Node node = addWaiter(Node.SHARED); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == head) { //如果當(dāng)前node的前繼時(shí)head,馬上嘗試搶占鎖 int r = tryAcquireShared(arg); if (r >= 0) { //如果state==0即允許往下執(zhí)行,重新設(shè)置head并往下傳播信號(hào) 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,或者原來(lái)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)備喚醒下一個(gè)節(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沒(méi)有改變,結(jié)束當(dāng)前l(fā)oop,如果遇到head被別的線程改變,繼續(xù)loop if (h == head) // loop if head changed break; } }
釋放鎖的信號(hào)一直向后傳播,直到所有node被喚醒并繼續(xù)執(zhí)行,那第一個(gè)信號(hào)時(shí)何時(shí)發(fā)起的呢?我們來(lái)看一下CountDownLatch的countDown方法,該方法調(diào)用了sync的releaseShared方法:
public final boolean releaseShared(int arg) { if (tryReleaseShared(arg)) { //如果同步狀態(tài)state為0時(shí),調(diào)用doReleaseShared,在這里就發(fā)出了第一個(gè)喚醒所有等待node的信號(hào),然后信號(hào)自動(dòng)往后傳播 doReleaseShared(); return true; } return false; }總結(jié)
CountDownLatch在調(diào)用await的時(shí)候判斷state釋放為0,如果大于0則阻塞當(dāng)前線程,將當(dāng)前線程的node添加到隊(duì)列中等待;在調(diào)用countDown時(shí)當(dāng)遇到state減到0時(shí),發(fā)出釋放共享鎖的信號(hào),從頭節(jié)點(diǎn)的后記節(jié)點(diǎn)開(kāi)始往后傳遞信號(hào),將隊(duì)列等待的線程逐個(gè)喚醒并繼續(xù)往下執(zhí)行;
在這里state跟Reentrant的state獨(dú)占鎖含義不同,state的含義是由AQS的子類去描述的。
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/70916.html
摘要:本文分析一下是如何運(yùn)用的是什么顧名思義它是一個(gè)門(mén)閂,它是用一個(gè)計(jì)數(shù)器實(shí)現(xiàn)的,初始狀態(tài)計(jì)數(shù)器的數(shù)值等于線程數(shù),每當(dāng)有線程完成任務(wù)后,計(jì)數(shù)器就會(huì)減一。當(dāng)為時(shí),鎖就會(huì)被釋放,凡是之前因搶占鎖而等待的線程這時(shí)候就會(huì)被喚醒繼續(xù)搶占鎖。 本文分析一下CountDownLatch是如何運(yùn)用AQS的 CountDownLatch是什么 CountDownLatch顧名思義它是一個(gè)Latch(門(mén)閂),它...
摘要:本文分析一下是如何運(yùn)用的是什么顧名思義它是一個(gè)門(mén)閂,它是用一個(gè)計(jì)數(shù)器實(shí)現(xiàn)的,初始狀態(tài)計(jì)數(shù)器的數(shù)值等于線程數(shù),每當(dāng)有線程完成任務(wù)后,計(jì)數(shù)器就會(huì)減一。當(dāng)為時(shí),鎖就會(huì)被釋放,凡是之前因搶占鎖而等待的線程這時(shí)候就會(huì)被喚醒繼續(xù)搶占鎖。 本文分析一下CountDownLatch是如何運(yùn)用AQS的 CountDownLatch是什么 CountDownLatch顧名思義它是一個(gè)Latch(門(mén)閂),它...
摘要:信號(hào)可以理解為一種許可,拿到許可的線程才可以繼續(xù)執(zhí)行。的計(jì)數(shù)器其實(shí)記錄的就是許可的數(shù)量,當(dāng)許可數(shù)量為時(shí),方法就會(huì)阻塞。 本文接著分析Semaphore的實(shí)現(xiàn)原理 Semaphore是什么 Semaphore是一個(gè)計(jì)數(shù)信號(hào)量。Semaphore(信號(hào))可以理解為一種許可,拿到許可的線程才可以繼續(xù)執(zhí)行。Semaphore的計(jì)數(shù)器其實(shí)記錄的就是許可的數(shù)量,當(dāng)許可數(shù)量為0時(shí),acquire方法...
摘要:信號(hào)可以理解為一種許可,拿到許可的線程才可以繼續(xù)執(zhí)行。的計(jì)數(shù)器其實(shí)記錄的就是許可的數(shù)量,當(dāng)許可數(shù)量為時(shí),方法就會(huì)阻塞。 本文接著分析Semaphore的實(shí)現(xiàn)原理 Semaphore是什么 Semaphore是一個(gè)計(jì)數(shù)信號(hào)量。Semaphore(信號(hào))可以理解為一種許可,拿到許可的線程才可以繼續(xù)執(zhí)行。Semaphore的計(jì)數(shù)器其實(shí)記錄的就是許可的數(shù)量,當(dāng)許可數(shù)量為0時(shí),acquire方法...
摘要:信號(hào)可以理解為一種許可,拿到許可的線程才可以繼續(xù)執(zhí)行。的計(jì)數(shù)器其實(shí)記錄的就是許可的數(shù)量,當(dāng)許可數(shù)量為時(shí),方法就會(huì)阻塞。 本文接著分析Semaphore的實(shí)現(xiàn)原理 Semaphore是什么 Semaphore是一個(gè)計(jì)數(shù)信號(hào)量。Semaphore(信號(hào))可以理解為一種許可,拿到許可的線程才可以繼續(xù)執(zhí)行。Semaphore的計(jì)數(shù)器其實(shí)記錄的就是許可的數(shù)量,當(dāng)許可數(shù)量為0時(shí),acquire方法...
閱讀 1492·2021-10-14 09:43
閱讀 1460·2021-10-09 09:58
閱讀 1953·2021-09-28 09:42
閱讀 3742·2021-09-26 09:55
閱讀 1772·2021-08-27 16:23
閱讀 2773·2021-08-23 09:46
閱讀 920·2019-08-30 15:55
閱讀 1449·2019-08-30 15:54