CountDownLatch类是一个同步计数器,构造时传入int参数,该参数就是计数器的初始值,每调用一次countDown()方法,计数器减1,计数器大于0 时,await()方法会阻塞程序继续执行。
CountDownLatch可以看作是一个倒计数的锁存器,当计数减至0时触发特定的事件。利用这种特性,可以让主线程等待子线程的结束
使用场景:有一个任务想要往下执行,但必须要等到其他的任务执行完毕后才可以继续往下执行。
1 public class CountDownLatchDemo { 2 final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 3 public static void main(String[] args) throws InterruptedException { 4 CountDownLatch latch=new CountDownLatch(2); 5 Worker worker1=new Worker("zhang san", 5000, latch); 6 Worker worker2=new Worker("li si", 8000, latch); 7 worker1.start(); 8 worker2.start(); 9 latch.await();10 System.out.println("all work done at "+sdf.format(new Date()));11 }12 13 14 static class Worker extends Thread{15 String workerName; 16 int workTime;17 CountDownLatch latch;18 public Worker(String workerName ,int workTime ,CountDownLatch latch){19 this.workerName=workerName;20 this.workTime=workTime;21 this.latch=latch;22 }23 public void run(){24 System.out.println("Worker "+workerName+" do work begin at "+sdf.format(new Date()));25 doWork();26 System.out.println("Worker "+workerName+" do work complete at "+sdf.format(new Date()));27 28 }29 30 private void doWork(){31 try {32 Thread.sleep(workTime);33 } catch (InterruptedException e) {34 e.printStackTrace();35 } finally {36 latch.countDown();37 }38 }39 }40 42 }43
参考:
http://www.iteye.com/topic/1002652
http://www.cnblogs.com/whgw/archive/2011/09/29/2195827.html