- 按照名字理解是 计数锁
- 用于多线程并行的同步,起栅栏作用
- 做法是利用计数器计算还未完成的任务数,直到计数为 0 的时候,才会往下执行
- 有点类似于线程对象的 join() 方法,都是等待子线程执行完毕再往下走
- 如果线程数大于计数器的数量,则同样计数为 0 的时候立刻往下执行
- 貌似挺简单的,需要根据业务场景灵活运用
- 下面看原理图
放码过来
public class TestCountDownLatch {
private static CountDownLatch cdl = new CountDownLatch(5);
static class TestThread implements Runnable {
@Override
public void run() {
try {
Thread.sleep(new Random().nextInt(10) * 1000);
System.out.println(System.currentTimeMillis() + " :" + Thread.currentThread().getName() + " 进来了,"
+ " 当前 countDown:" + cdl.getCount());
cdl.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("======= 开始测试 CountDownLatch =======");
Thread[] threads = new Thread[10];
TestThread read = new TestThread();
for (int i = 0; i < threads.length; i++) threads[i] = new Thread(read, "线程 " + i);
for (int i = 0; i < threads.length; i++) threads[i].start();
cdl.await();
System.out.println("======= 全部线程检查完毕,程序退出 =======");
}
}
======= 开始测试 CountDownLatch =======
1537881097774 :线程 8 进来了, 当前 countDown:5
1537881097774 :线程 2 进来了, 当前 countDown:5
1537881097774 :线程 6 进来了, 当前 countDown:5
1537881098775 :线程 0 进来了, 当前 countDown:2
1537881100775 :线程 1 进来了, 当前 countDown:1
1537881100775 :线程 4 进来了, 当前 countDown:1
======= 全部线程检查完毕,程序退出 =======
1537881101775 :线程 5 进来了, 当前 countDown:0
1537881104775 :线程 3 进来了, 当前 countDown:0
1537881105775 :线程 9 进来了, 当前 countDown:0
1537881106775 :线程 7 进来了, 当前 countDown:0
这里要提一下的是:
- CountDownLatch 不能重复使用,countDown 完了只能重新实例化一个出来