java.util.concurrency中的CountDownLatch,主要用于等待一個(gè)或多個(gè)其他線程完成任務(wù)。CountDownLatch在初始化時(shí)逊抡,會(huì)被賦一個(gè)整數(shù)派诬,每次執(zhí)行countDown()方法劳淆,該整數(shù)都會(huì)減一,直至到0默赂,這一過程不可逆轉(zhuǎn)沛鸵。其await()方法會(huì)在該整數(shù)不為0時(shí)當(dāng)前線程阻塞,為0時(shí)當(dāng)前線程進(jìn)行下去。阻塞時(shí)曲掰,其他線程得到執(zhí)行疾捍。
下面是一個(gè)普通的案例:
Player
import java.util.Random;
import java.util.concurrent.CountDownLatch;
public class Player implements Runnable {
private CountDownLatch begin;
private CountDownLatch end;
private String playerNO;
public Player(String playerNO, CountDownLatch begin, CountDownLatch end) {
this.playerNO = playerNO;
this.begin = begin;
this.end = end;
}
@Override
public void run() {
// 等待槍響
try {
begin.await();
long timeUsed = new Random().nextInt(10000);
Thread.sleep(timeUsed);
System.out.println("運(yùn)動(dòng)員" + playerNO + "耗時(shí)" + timeUsed + "完成比賽");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
end.countDown();
}
}
}
OlympicsGame
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class OlympicsGame {
private static final int PLAYER_SIZE = 5;
private CountDownLatch begin;
private CountDownLatch end;
public CountDownLatch getBegin() {
return begin;
}
public void setBegin(CountDownLatch begin) {
this.begin = begin;
}
public CountDownLatch getEnd() {
return end;
}
public void setEnd(CountDownLatch end) {
this.end = end;
}
public OlympicsGame() {
begin = new CountDownLatch(1);
end = new CountDownLatch(PLAYER_SIZE);
}
public static void main(String[] args) {
// 舉辦一場(chǎng)比賽
OlympicsGame olympic = new OlympicsGame();
// 設(shè)定比賽開始,槍聲
CountDownLatch begin = olympic.getBegin();
// 所有運(yùn)動(dòng)員結(jié)束比賽栏妖,才算結(jié)束比賽
CountDownLatch end = olympic.getEnd();
// 運(yùn)動(dòng)員進(jìn)場(chǎng)乱豆,并編號(hào),等待槍響
Player[] players = new Player[PLAYER_SIZE];
ExecutorService ex = Executors.newFixedThreadPool(PLAYER_SIZE);
for (int i = 0; i < 5; i++) {
players[i] = new Player("NO" + (i + 1), begin, end);
ex.submit(players[i]);
}
// 槍響
begin.countDown();
try {
// 等待所有運(yùn)動(dòng)員到達(dá)終點(diǎn)
end.await();
System.out.println("比賽結(jié)束,所有運(yùn)動(dòng)員完成比賽");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
某次執(zhí)行結(jié)果是: