前言
CountDownLatch 用于使一組線程(1 or n)等待一個(gè)外部任務(wù)的完成菜秦。很多人將它稱為閉鎖呆盖,可以理解為鎖的就是那些線程挺邀,然后需要一個(gè)外部任務(wù)的完成來觸發(fā)比鎖打開幢尚。主要場景的話瑰妄,等待資源加載完畢米同、檢查接口是否正常 再執(zhí)行骇扇。或者取到各種數(shù)據(jù)后再入庫面粮。還有經(jīng)常用于喚醒大量而不是全部的線程去執(zhí)行任務(wù)匠题。
CountDownLatch demo的代碼量有點(diǎn)多,這個(gè)大家百度一下就ok了但金,這一篇主要說原理韭山。
CountDownLatch 可以看為一個(gè)簡單的計(jì)數(shù)器,等待的任務(wù)數(shù)量為n冷溃,如果任務(wù)都完成了(countDown)則代表整體ok钱磅。
源碼
源碼量非常小,可以理解為僅僅依賴于AQS實(shí)現(xiàn)了一個(gè)計(jì)數(shù)器似枕,只不過這個(gè)計(jì)數(shù)器持有一堆等待線程盖淡。
首先里面包含一個(gè)Sync,想必看過前兩篇文章的同學(xué)對于這個(gè)已經(jīng)很容易理解了凿歼,就是一個(gè)AQS褪迟,然后這個(gè)Sync中持有的state就是count,用來顯示等待完成的數(shù)量答憔。當(dāng)state為0時(shí)放行味赃。通過CAS完成狀態(tài)的更新,然后很顯然CountDownLatch是一次性的虐拓,每次初始化心俗,然后減小。
package java.util.concurrent;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
public class CountDownLatch {
/**
* Synchronization control For CountDownLatch.
* Uses AQS state to represent count.
*/
private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4982264981922014374L;
Sync(int count) {
setState(count);
}
int getCount() {
return getState();
}
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();
if (c == 0)
return false;
int nextc = c - 1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}
private final Sync sync;
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
public void countDown() {
sync.releaseShared(1);
}
public long getCount() {
return sync.getCount();
}
public String toString() {
return super.toString() + "[Count = " + sync.getCount() + "]";
}
}