一、简介
- countDownLatch存在于java.util.cucurrent包下
- countDownLatch这个类使一个线程等待其他线程各自执行完毕后再执行。
- countDownLatch通过一个计数器来实现的,计数器的初始值是线程的数量。每当一个线程执行完毕后,计数器的值就-1,当计数器的值为0时,表示所有线程都执行完毕,然后在闭锁上等待的线程就可以恢复工作了。
二、源码介绍
countDownLatch类中只提供了一个构造器
//参数count为计数值,且不能小于0
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
类中有三个方法是最重要的:
//调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
public void await() throws InterruptedException { };
//和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
public boolean await(long timeout, TimeUnit unit) throws InterruptedException { };
//将count值减1
public void countDown() { };
三、CountDownLatch用法
countDownLatch的用法也比较简单,这里我们用两个小案例来了解一下。
案例一:教室里有六个人,当六个人全出去之后,关掉教室门
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch=new CountDownLatch(6);
for(int i=1;i<=6;i++){
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"Go out");
countDownLatch.countDown(); //数量减一
},String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println("Close Door");
}
}
案例二:简单模拟刘关张桃园三结义
import java.util.concurrent.CountDownLatch;
/**
* Author: 徐志
* Date: 2020/8/8 16:44
*/
public class CountDownLatchDemo2 {
public static void main(String[] args) {
CountDownLatch countDownLatch=new CountDownLatch(2);
new Thread(()->{
System.out.println("刘备--》在等待");
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("刘关张桃园三结义");
}).start();
new Thread(()->{
System.out.println("张飞--》骑马而来");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
System.out.println("张飞拜见大哥");
}).start();
new Thread(()->{
System.out.println("关羽--》骑马而来");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
System.out.println("关羽拜见大哥");
}).start();
}
}
以上就是CountDownLatch的简单用法了,还是非常方便的。附上本人微信公众号二维码,本人也在学习汇总,欢迎大家一起交流学习