import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 倒计时器:CountDownLatch * 通常用来控制线程等待,可以让某一个线程等待直到倒计时结束,再开始执行 */ public class CountDownLatchDemo implements Runnable{ static final CountDownLatch end = new CountDownLatch(10);//当前计算器的计数个数10 static final CountDownLatchDemo demo = new CountDownLatchDemo(); @Override public void run() { try { //模拟检查任务 Thread.sleep(new Random().nextInt(10)*1000); System.out.println("check complete"); end.countDown();//通知CountDownLatch一个线程完成任务,倒计时器减1 } catch (InterruptedException e) { e.printstacktrace(); } } public static void main(String[] args) throws InterruptedException{ ExecutorService exec = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; i++) { exec.submit(demo); } //等待检查 end.await();//主线程等待所有检查任务全部完成 System.out.println("ok"); exec.shutdown(); } }