1. package com.atguigu.sh.juc.study03;
    2. import java.util.concurrent.CountDownLatch;
    3. /**
    4. *
    5. * 【第七节】
    6. *
    7. * JUC强大的辅助类一: CountDownLatch.class
    8. * CountDownLatch countDownLatch = new CountDownLatch(6);
    9. * 线程执行时,调用CountDownLatch对象的countDown()方法,进行倒数;
    10. * 然后调用CountDownLatch对象的countDown对象的await()方法后的逻辑,会在countDown()到0的时候才调用;
    11. *
    12. *
    13. * 假设模拟学生上自习,班长等学生离开教室,进行关门的场景;
    14. * 一定要所有的学生都离开教室(所有的线程都运行完毕),班长才能关门
    15. *
    16. *
    17. */
    18. public class CountDownLatchDemo {
    19. public static void main(String[] args) throws InterruptedException {
    20. CountDownLatch countDownLatch = new CountDownLatch(6);
    21. for (int i = 1; i <= 6 ; i++) {
    22. new Thread(() -> {
    23. System.out.println(Thread.currentThread().getName()+"\t离开教室");
    24. countDownLatch.countDown();
    25. }, String.valueOf(i)).start();
    26. }
    27. countDownLatch.await();
    28. System.out.println("main---班长关门走人");
    29. }
    30. private static void errorCloseDoor() {
    31. for (int i = 1; i <= 6 ; i++) {
    32. new Thread(() -> {
    33. System.out.println(Thread.currentThread().getName()+"\t离开教室");
    34. }, String.valueOf(i)).start();
    35. }
    36. System.out.println("main---班长关门走人");
    37. }
    38. }