一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
用给定的计数 初始化 CountDownLatch
。由于调用了 countDown()
方法,所以在当前计数到达零之前,await
方法会一直受阻塞。之后,会释放所有等待的线程,await
的所有后续调用都将立即返回。这种现象只出现一次——计数无法被重置。如果需要重置计数,请考虑使用 CyclicBarrier
。
CountDownLatch
是一个通用同步工具,它有很多用途。将计数 1 初始化的 CountDownLatch
用作一个简单的开/关锁存器,或入口:在通过调用 countDown()
的线程打开入口前,所有调用 await
的线程都一直在入口处等待。用 N 初始化的 CountDownLatch
可以使一个线程在 N个线程完成某项操作之前一直等待,或者使其在某项操作完成 N 次之前一直等待。
CountDownLatch
的一个有用特性是,它不要求调用 countDown
方法的线程等到计数到达零时才继续,而在所有线程都能通过之前,它只是阻止任何线程继续通过一个 await
。
CountDownLatch主要起倒计时计数器作用,它主要有两个方法await()和countDown()。一旦某个线程调用await() 方法,那么该线程就会阻塞,等待CountDownLatch计数器倒计时归零,需要注意的是尽管线程调用await()方法后会阻塞,但是 CountDownLatch允许别的线程调用countDown()方法,将计数器减一。也就是说调用计时器的线程阻塞后,可以利用别的线程控制调用线 程何时从新开始运行。
Example:

1 package com.my.hqb; 2 3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 import java.util.concurrent.CountDownLatch; 6 7 public class CountDownLatchExample implements Runnable{ 8 9 private CountDownLatch countDownLatch; 10 11 public CountDownLatchExample(CountDownLatch countDownLatch){ 12 this.countDownLatch = countDownLatch; 13 } 14 15 @Override 16 public void run() { 17 try { 18 System.out.println("I am started, " + Thread.currentThread().getName() + ", " + new SimpleDateFormat("hh:mm:ss").format(new Date())); 19 Thread.sleep(5000); 20 this.countDownLatch.countDown(); 21 } catch (InterruptedException e) { 22 // TODO Auto-generated catch block 23 e.printStackTrace(); 24 } 25 } 26 27 public static void main(String [] args) throws InterruptedException{ 28 CountDownLatch latch = new CountDownLatch(3); 29 30 for(int i=0;i<3;i++){ 31 new Thread(new CountDownLatchExample(latch)).start(); 32 } 33 34 latch.await(); 35 36 System.out.println("All finished, " + new SimpleDateFormat("hh:mm:ss").format(new Date())); 37 } 38 }