- 倒计时门闩
- 设定一个值,完成一个进行一次countDown,结束之后就开了(await的地方就能继续向下了)
- 门闩在那拴住门,不让他向下执行\
- 滚动发车===>坐满就走
- 与join实现的功能差不多
- 与join效率相比应该差不多===>但是一般这种阻塞的方法不谈效率===>运行的线程运行多长时间才应该算效率
- 门闩控制得比join灵活不少!!!(可以更加个性化)
package com.mashibing.juc.c_020;import java.util.concurrent.CountDownLatch;public class T06_TestCountDownLatch { public static void main(String[] args) { usingJoin(); usingCountDownLatch(); } private static void usingCountDownLatch() { Thread[] threads = new Thread[100]; CountDownLatch latch = new CountDownLatch(threads.length); for(int i=0; i<threads.length; i++) { threads[i] = new Thread(()->{ int result = 0; for(int j=0; j<10000; j++) result += j; latch.countDown(); }); } for (int i = 0; i < threads.length; i++) { threads[i].start(); } try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("end latch"); } private static void usingJoin() { Thread[] threads = new Thread[100]; for(int i=0; i<threads.length; i++) { threads[i] = new Thread(()->{ int result = 0; for(int j=0; j<10000; j++) result += j; }); } for (int i = 0; i < threads.length; i++) { threads[i].start(); } for (int i = 0; i < threads.length; i++) { try { threads[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("end join"); }}