package com.thread.test.Lock; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CountDownLatchDemo implements Runnable { static final CountDownLatch end = new CountDownLatch(10);// 创建倒计时器,表示需要等待10个线程,等待在CountDownLatch上的线程才能继续执行 static final CountDownLatchDemo DEMO = new CountDownLatchDemo(); public void run() { try { Thread.sleep(new Random().nextInt(10) * 1000); System.out.println(Thread.currentThread().getName() + "----check complete"); end.countDown();// 通知倒计时器一个线程完事儿,倒计时器减1 } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { // 使用倒计时器来模仿火箭发射 ExecutorService exec = Executors.newFixedThreadPool(10);// 创建10个线程的线程池 for (int i = 0; i < 10; i++) { exec.submit(DEMO); } end.await();// 倒计时器需要等待10个线程的任务全部完成后,主线程才能继续执行 System.out.println("火箭发射"); exec.shutdown();// 关闭线程池 } }