- CountDownLatch是一个同步辅助工具,用于使一个或多个线程等待(即阻塞)知道一组在其他线程中的任务结束。
- CountDownLatch必须用给定的count(一个int类型的大于等于0的值)进行初始化。调用await方法将使线程阻塞,直到当前计数(count值)由于countdown方法的调用而达到零,此后所有等待的线程被释放并且任何后续调用await方法也会立即返回。CountDownLatch被设计为只触发一次,即Count值在运行过程中无法重置。如果需要重置计数的版本,可以考虑使用CyclicBarrier.
- CountDownLatch是一种通用的同步工具。 CountDownLatch可以被认为是一个简单的on/off锁存器或门:所有线程调用await方法等待开关打开,直到countDown方法被调用打开开关为止。 创建一个CountDownLatch,指定count的值为N,那么这个CountDownLatch对象可以让一个线程等待其他N个线程结束(调用countDown方法即认为结束),或者调用了这个CountDownLatch的countDown方法N次。
测试代码如下:
public class ThreadWait { public static void main(String[] args) throws InterruptedException { ExecutorService exector = Executors.newFixedThreadPool(5); int threadNumber = 13; final CountDownLatch countDownLatch = new CountDownLatch(threadNumber); for (int i = 0; i < threadNumber; i++) { final int threadID = i; exector.execute( () -> { try { Thread.sleep(2000); System.out.println(String.format("threadID:[%s] finished!!", threadID)); } catch (InterruptedException e) { e.printStackTrace(); } finally { countDownLatch.countDown(); //这个不管是否异常都需要数量减,否则会被堵塞无法结束 } } ); } countDownLatch.await();//保证之前的所有的线程都执行完成,才会走下面的 System.out.println(countDownLatch.getCount()); System.out.println("main thread finished!!"); } } 结果为: threadID:[0]finished!! threadID:[1]finished!! threadID:[4]finished!! threadID:[3]finished!! threadID:[2]finished!! threadID:[9]finished!! threadID:[8]finished!! threadID:[5]finished!! threadID:[6]finished!! threadID:[7]finished!! threadID:[10]finished!! threadID:[11]finished!! threadID:[12]finished!! 0 main thread finished!!