同时等待 N 个任务执行结束.
好像跑步比赛,10个选手进行比赛, 所有选手都通过终点,才能公布成绩。
代码示例:
class Test{
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(10);
Random random = new Random();
Runnable runnable = new Runnable() {
@Override
public void run() {
int time = random.nextInt(3);
try {
Thread.sleep(time*1000);
System.out.println(Thread.currentThread().getName() + "跑到终点了!");
// 线程跑到终点了
latch.countDown();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
for (int i = 0; i < 10; i++) {
Thread t = new Thread(runnable);
t.start();
}
// 必须等到 10 个线程都跑到终点才继续执行
latch.await();
System.out.println("10 个线程都已跑到终点");
}
}
实际开发中 CountDownLatch 也是有许多应用场景的,
比如下载一个大文件, 如 视频,好几个 G,