CountDownLatch是一个非常实用的多线程控制工具类
常用方法有三个
CountDownLatch(int count) // 实例化一个倒计数器,count指定计数个数
countDown() // 计数减一
await() // 等待,当计数减到0时,所有线程并行执行
未使用CountDownLatch的代码:
public class Demo {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"\t 工作任务完成,离开公司");
},String.valueOf(i)).start();
}
System.out.println(Thread.currentThread().getName()+"\t 最后将公司门锁死,离开公司");
}
}
控制台结果:
使用CountDownLatch的代码:
public class Demo {
public static void main(String[] args) throws Exception{
CountDownLatch countDownLatch = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"\t 工作任务完成,离开公司");
countDownLatch.countDown();
},String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName()+"\t 最后将公司门锁死,离开公司");
}
}
控制台结果: