CountDownLatch使用场景
线程计数器 用于线程执行任务,计数 等待线程结束
测试代码:
@Log4j2
public class CountDownLatchController {
public static void main(String[] args) {
//线程数10
ExecutorService threadPool = Executors.newFixedThreadPool(10);
try {
//获取数量5
List<String> ids = getMap();
//赋值CountDownLatch线程计数5
CountDownLatch countDownLatch = new CountDownLatch(ids.size());
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
for (String id : ids) {
//异步处理
threadPool.submit(new Runnable() {
@Override
public void run() {
try {
System.out.println("id = "+id + "时间 = "+df.format(LocalDateTime.now(ZoneOffset.of("+8"))) + " 线程 = "+Thread.currentThread().getName());
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}finally {
//线程计数减1
countDownLatch.countDown();
}
}
});
}
//等待线程计算为0 或者 等待一分钟还不为0则不等待了
countDownLatch.await(1,TimeUnit.MINUTES);
System.out.println("我是小张啊 " + "时间 = "+df.format(LocalDateTime.now(ZoneOffset.of("+8"))) + " 线程 = "+Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//关闭线程池
threadPool.shutdown();
}
}
public static List<String> getMap(){
List<String> ids = new ArrayList<>();
for (int i = 0; i < 5; i++) {
ids.add(i+"");
}
return ids;
}
}
测试结果: