一、导读
CountDownLatch可以保证程序在子线程都执行完毕的情况下再执行主线程。
使用方法:对CountDownLatch对象设置初值,每个线程执行完后调用countDown方法,计数器减1,
当所有线程都执行完毕后,计数器为0,继续执行主线程逻辑。
二、代码示例
package com.hanshimeng.other;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Java线程池ExecutorService和CountDownLatch的简单示例
* 模拟了100米赛跑,10名选手已经准备就绪,只等裁判一声令下。当所有人都到达终点时,比赛结束。
* @author hanshimeng
*
*/
public class Competition{
public static void main(String[] args) throws InterruptedException {
//10名运动员
final CountDownLatch count = new CountDownLatch(10);
//java的线程池
final ExecutorService executorService = Executors.newFixedThreadPool(5);
for(int index=1;index<=10;index++){
final int number = index;
executorService.submit(new Runnable() {
public void run() {
try {
Thread.sleep((long) (Math.random()*10000));
System.out.println(number+"号运动员已经抵达终点");
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
//运动员到达终点,count数减一
count.countDown();
}
}
});
}
System.out.println("比赛开始");
//等待count数变为0,否则会一直处于等待状态,游戏就没法结束了
count.await();
System.out.println("比赛结束");
//关掉线程池
executorService.shutdown();
}
}
比赛结果:
比赛开始
2号运动员已经抵达终点
1号运动员已经抵达终点
4号运动员已经抵达终点
3号运动员已经抵达终点
6号运动员已经抵达终点
7号运动员已经抵达终点
9号运动员已经抵达终点
5号运动员已经抵达终点
8号运动员已经抵达终点
10号运动员已经抵达终点
比赛结束
如需转载,请注明作者出处
作者:hanshimeng
出处:https://blog.youkuaiyun.com/hanshimeng