CountDownLatch使用

public class CountDownLatchDemo {
    public static void main(String[] args) throws Exception {
        CountDownLatch countDownLatch = new CountDownLatch(54);
        for (int i = 1; i < 55; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"走出教室");
                countDownLatch.countDown();
            },""+String.valueOf(i)+"同学").start();
        }
        countDownLatch.await();
        System.out.println("同学们走完了,锁门了");
    }
}

运行结果:

第1同学走出教室
第4同学走出教室
第3同学走出教室
第2同学走出教室
第6同学走出教室
第7同学走出教室
。。。
第52同学走出教室
第51同学走出教室
第53同学走出教室
第54同学走出教室
同学们走完了,锁门了

CountDownLatch countDownLatch = new CountDownLatch(1);//模拟互斥

原文地址:https://www.cnblogs.com/flgb/p/11788965.html