一睛挚、概念
CountDownLatch 是java.util.concurrent中的一個(gè)同步工具類铜幽,用來協(xié)調(diào)多個(gè)線程之間的同步,或者說起到線程之間的通信(而不是互斥)的作用玛歌。機(jī)制是只要提供的多個(gè)(具體數(shù)量等于初始化CountDownLatch時(shí)count的值)線程都達(dá)到了預(yù)期狀態(tài)或者完成了預(yù)期工作時(shí)觸發(fā)事件背蟆,其他線程可以等待這個(gè)事件來觸發(fā)自己后續(xù)的工作毛仪。
等待的線程可以是多個(gè)排嫌,即 CountDownLatch 可以喚醒多個(gè)等待的線程。到達(dá)自己預(yù)期狀態(tài)的線程會調(diào)用 CountDownLatch 的 countDown()仿吞,而等待的線程會調(diào)用 CountDownLatch 的 await()滑频。
CountDownLatch 能夠使一個(gè)線程在等待另外一些線程完成各自工作之后,再繼續(xù)執(zhí)行唤冈。計(jì)數(shù)器初始值為線程的數(shù)量峡迷。當(dāng)每一個(gè)線程完成自己任務(wù)后,計(jì)數(shù)器的值就會減 1。當(dāng)計(jì)數(shù)器的值為 0 時(shí)绘搞,表示所有的線程都已經(jīng)完成一些任務(wù)彤避,然后在 CountDownLatch 上等待的線程就可以恢復(fù)執(zhí)行接下來的任務(wù)。
注意:它是一次性的夯辖,計(jì)算器的值只能在構(gòu)造方法中初始化一次琉预,之后再?zèng)]有任何機(jī)制對其設(shè)置值,當(dāng) CountDownLatch 使用完畢后楼雹,它不能再次被使用模孩。
二、用法
1??某一線程在開始運(yùn)行前等待 n 個(gè)線程執(zhí)行完畢贮缅。CountDownLatch 的計(jì)數(shù)器初始化new CountDownLatch(n)
,每當(dāng)一個(gè)任務(wù)線程執(zhí)行完畢介却,就將計(jì)數(shù)器減 1 即執(zhí)行countdownLatch.countDown()
谴供,當(dāng)計(jì)數(shù)器的值變?yōu)?0 時(shí),在 CountDownLatch 上 await() 的線程就會被喚醒齿坷。一個(gè)典型應(yīng)用場景就是啟動(dòng)一個(gè)服務(wù)時(shí)桂肌,主線程需要等待多個(gè)組件加載完畢,之后再繼續(xù)執(zhí)行永淌。
2??實(shí)現(xiàn)多個(gè)線程開始執(zhí)行任務(wù)的最大并行性崎场。注意是并行性,不是并發(fā)遂蛀,強(qiáng)調(diào)的是多個(gè)線程在某一時(shí)刻同時(shí)開始執(zhí)行谭跨。類似于賽跑,將多個(gè)線程放到起點(diǎn)李滴,等待發(fā)令槍響螃宙,然后同時(shí)開跑。做法是初始化一個(gè)共享的 CountDownLatch(1)所坯,將其計(jì)算器初始化為 1谆扎,多個(gè)線程在開始執(zhí)行任務(wù)前首先 countdownlatch.await(),當(dāng)主線程調(diào)用 countDown() 時(shí)芹助,計(jì)數(shù)器變?yōu)?0堂湖,多個(gè)線程同時(shí)被喚醒。
三状土、方法說明
1??public void countDown()
遞減鎖存器的計(jì)數(shù)无蜂,如果計(jì)數(shù)到達(dá)零,則釋放所有等待的線程声诸。如果當(dāng)前計(jì)數(shù)大于零酱讶,則將計(jì)數(shù)減少。
2??public void await() throws InterruptedException { };
調(diào)用該方法的線程會被掛起彼乌,它會等待直到 count 值為 0 才繼續(xù)執(zhí)行泻肯。
3??public boolean await(long timeout,TimeUnit unit) throws InterruptedException
timeout---要等待的最長時(shí)間渊迁;unit---timeout 參數(shù)的時(shí)間單位。和 await() 類似灶挟,只不過等待一定的時(shí)間后 count 值還沒變?yōu)?0 的話就會繼續(xù)執(zhí)行琉朽。
使當(dāng)前線程在鎖存器倒計(jì)數(shù)至零之前一直等待,除非線程被中斷或超出了指定的等待時(shí)間稚铣。如果當(dāng)前計(jì)數(shù)為零箱叁,此方法立刻返回 true。如果當(dāng)前計(jì)數(shù)大于零惕医,出于線程調(diào)度目的耕漱,將禁用當(dāng)前線程,且在發(fā)生以下三種情況之一前抬伺,該線程將一直出于休眠狀態(tài):
- 由于調(diào)用 countDown()螟够,計(jì)數(shù)到達(dá)零。
- 其他某個(gè)線程中斷當(dāng)前線程峡钓。
- 已超出指定的等待時(shí)間妓笙。
- 如果計(jì)數(shù)到達(dá)零,該方法返回 true能岩。
- 如果當(dāng)前線程寞宫,在進(jìn)入此方法時(shí)已經(jīng)設(shè)置了該線程的中斷狀態(tài);或者在等待時(shí)被中斷拉鹃,則拋出 InterruptedException辈赋,并且清除當(dāng)前線程的已中斷狀態(tài)。
- 如果超出了指定的等待時(shí)間毛俏,則返回 false炭庙。如果該時(shí)間小于等于零,則該方法根本不會等待煌寇。
四焕蹄、方法示例
1??主線程等待子線程執(zhí)行完成再執(zhí)行
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountdownLatchTest1 {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(3);
final CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("子線程" + Thread.currentThread().getName() + "開始執(zhí)行");
Thread.sleep((long) (Math.random() * 10000));
System.out.println("子線程" + Thread.currentThread().getName() + "執(zhí)行完成");
latch.countDown();//當(dāng)前線程調(diào)用此方法,則計(jì)數(shù)減1
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
service.execute(runnable);
}
try {
System.out.println("主線程" + Thread.currentThread().getName() + "等待子線程執(zhí)行完成...");
latch.await();//阻塞當(dāng)前線程阀溶,直到計(jì)數(shù)器的值為0
service.shutdown();
System.out.println("主線程" + Thread.currentThread().getName() + "開始執(zhí)行...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2??百米賽跑腻脏,4 名選手等待裁判口令,裁判一聲口令银锻,選手聽到后同時(shí)起跑永品,當(dāng)所有選手到達(dá)終點(diǎn),裁判進(jìn)行匯總排名
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountdownLatchTest2 {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final CountDownLatch cdOrder = new CountDownLatch(1);
final CountDownLatch cdAnswer = new CountDownLatch(4);
for (int i = 0; i < 4; i++) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("選手" + Thread.currentThread().getName() + "正在等待裁判發(fā)布口令");
cdOrder.await();
System.out.println("選手" + Thread.currentThread().getName() + "已接受裁判口令");
Thread.sleep((long) (Math.random() * 10000));
System.out.println("選手" + Thread.currentThread().getName() + "到達(dá)終點(diǎn)");
cdAnswer.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
service.execute(runnable);
}
try {
Thread.sleep((long) (Math.random() * 10000));
System.out.println("裁判" + Thread.currentThread().getName() + "即將發(fā)布口令");
cdOrder.countDown();
System.out.println("裁判" + Thread.currentThread().getName() + "已發(fā)送口令击纬,正在等待所有選手到達(dá)終點(diǎn)");
cdAnswer.await();
System.out.println("所有選手都到達(dá)終點(diǎn)");
System.out.println("裁判" + Thread.currentThread().getName() + "匯總成績排名");
} catch (InterruptedException e) {
e.printStackTrace();
}
service.shutdown();
}
}
3??確保三個(gè)線程順序執(zhí)行
import java.util.concurrent.CountDownLatch;
public class CountdownLatchTest3 {
// T1鼎姐、T2、T3三個(gè)線程順序執(zhí)行
public static void main(String[] args) {
CountDownLatch c0 = new CountDownLatch(0); //計(jì)數(shù)器為0
CountDownLatch c1 = new CountDownLatch(1); //計(jì)數(shù)器為1
CountDownLatch c2 = new CountDownLatch(1); //計(jì)數(shù)器為1
//c0為0,t1可以執(zhí)行炕桨。t1的計(jì)數(shù)器減1
Thread t1 = new Thread(new Work(c0, c1));
//t1的計(jì)數(shù)器為0時(shí)饭尝,t2才能執(zhí)行。t2的計(jì)數(shù)器c2減1
Thread t2 = new Thread(new Work(c1, c2));
//t2的計(jì)數(shù)器c2為0時(shí)献宫,t3才能執(zhí)行
Thread t3 = new Thread(new Work(c2, c2));
t1.start();
t2.start();
t3.start();
}
//定義Work線程類钥平,需要傳入開始和結(jié)束的CountDownLatch參數(shù)
static class Work implements Runnable {
CountDownLatch c1;
CountDownLatch c2;
Work(CountDownLatch c1, CountDownLatch c2) {
super();
this.c1 = c1;
this.c2 = c2;
}
public void run() {
try {
c1.await();//前一線程為0才可以執(zhí)行
System.out.println("thread start:" + Thread.currentThread().getName());
c2.countDown();//本線程計(jì)數(shù)器減少
} catch (InterruptedException e) {
}
}
}
}