CountDownLatch类是JUC包里面的一个倒计时控制类,类似是火箭发射倒计时,具体实现如下:
package com.atnuocai.model;import java.util.concurrent.CountDownLatch;/*** Created by on 27/11/2021*java.util.CountDownLatch(火箭发射倒计时)* 让一线程阻塞直到另一些线程完成一系列操作才被唤醒。** CountDownLatch主要有两个方法(await(),countDown())。** 当一个或多个线程调用await()时,调用线程会被阻塞。其它线程调用countDown()会将计数器减1(调用countDown方法的线程不会阻塞),当计数器的值变为零时,因调用await方法被阻塞的线程会被唤醒,继续执行* @author 刘杰杰*/
public class CountDownLatchDemo {public static void main(String[] args) throws Exception{// unUseCountDown();// useCountDown();//秦灭六国,统一华夏CountDownLatch countDownLatch = new CountDownLatch(6);for (int i = 1; i <= 6; i++) {new Thread(()->{System.out.println(Thread.currentThread().getName()+"被灭");countDownLatch.countDown();},CountryEnum.getCountry(i).getReCountry()).start();}countDownLatch.await();System.out.println("==============");System.out.println("秦灭六国,统一华夏");}/*** 使用CountDownLatch之后* @throws InterruptedException*/private static void useCountDown() throws InterruptedException {CountDownLatch countDownLatch = new CountDownLatch(6);for (int i = 1; i <= 6; i++) {new Thread(()->{System.out.println("学生"+Thread.currentThread().getName()+"离开教室");countDownLatch.countDown();},String.valueOf(i)).start();}countDownLatch.await();System.out.println("===================");System.out.println("班长最后离开教室");}/*** 未使用CountDownLatch方法之前*/private static void unUseCountDown() {for (int i = 1; i <= 6; i++) {new Thread(()->{System.out.println("学生"+ Thread.currentThread().getName() +"离开教室!");},String.valueOf(i)).start();}System.out.println("=============");System.out.println("班长最后离开教室");}
}