1、是什么?
這是一個計數(shù)器,而且是倒計時。就像火箭發(fā)射,10,9,8,……,0,到了0火箭才會發(fā)射。這個也一樣,當里面的線程執(zhí)行完,外面的線程才會執(zhí)行。用一句話講就是:秦滅六國,一統(tǒng)華夏。滅六國是是六個線程,等這六個線程執(zhí)行完,一統(tǒng)華夏這個線程才能進行。
2、怎么用?
3、用之前怎么樣?
話不多說,直接擼代碼:
1public static void main(String[] args) throws Exception{
2 for (int i = 1; i <= 6; i++) {
3 final int temp = i;
4 new Thread(() -> {
5 System.out.println("第 " + temp + "個國家被滅!");
6 }, "i").start();
7 }
8 System.out.println("六國被滅,秦一統(tǒng)華夏!");
9}
我們的本意是:循環(huán)里面的六個線程執(zhí)行完,主線程才能輸出“六國被滅,秦一統(tǒng)華夏!”這句換,看看執(zhí)行結(jié)果是否如嘗所愿:
運行結(jié)果才滅了三個國家,那統(tǒng)一個錘子。
4、用之后怎么樣?
1 public static void main(String[] args) throws Exception{
2 CountDownLatch count = new CountDownLatch(6);
3 for (int i = 1; i <= 6; i++) {
4 final int temp = i;
5 new Thread(() -> {
6 System.out.println("第 " + temp + "個國家被滅!");
7 count.countDown();
8 }, "i").start();
9 }
10 count.await();
11 System.out.println("六國被滅,秦一統(tǒng)華夏!");
12 }
運行結(jié)果
這就符合了預(yù)期。