倒计时:CountDownLatch(火箭发射前的准备)读书笔记
这是一个非常实用的多线程控制工具类,经典的场景就是 火箭发射,在火箭发射前,为了保证万无一失,往往还要进行各项设备,仪器的检查,只有等待所有的检查完毕后,引擎才能点火,
CountDownLatch构造器接受一个整数作为参数,即当前这个计数器的计数个数.
public CountDownLatch(int count)
下面这个简单是的示例,演示了CountDownLatch的使用.
public class CountDownLatchDemo implements Runnable { static final CountDownLatch end = new CountDownLatch(10); static final CountDownLatchDemo demo = new CountDownLatchDemo(); /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see Thread#run() */ @Override public void run() { try { Thread.sleep(new Random().nextInt(10) * 1000); System.out.println("check complete"); end.countDown();//完成 可以减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();//主线程等待所有10个线程完成任务 才能继续执行 System.out.println("Fire!"); exec.shutdown(); } }
计数数量为10,这表示需要10个线程完成任务,等待在CountDownLatch上的线程才能继续执行,CountDownLatch.countdown()方法,也就是通知CountDownLatch,一个线程已经完成了任务倒计时器可以减1啦,使用CountDownLatchawait()方法,要求主线程等待所有10个检查任务全部完成.待10个任务全部完成后,主线程才能继续执行.
主线程在CountDownLatch上等待,当所有检查任务全部完成后,主线程方能继续执行,