CountDownLatch使用场景
主程序等待所有子程序执行完成后才开始执行。
若计数器的数量大于子线程的数量,即计数器没有减到0,则线程一直处于await状态。
package com.learn.thread.countdown;
import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;
public class CountDownTest {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(3);
IntStream.range(0, 3).forEach(i -> new Thread(() -> {
try {
Thread.sleep(2000);
System.out.println("child thread");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
}).start());
System.out.println("启动子线程完毕");
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程执行完毕");
}
}