import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws Exception {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+" 国,被灭");
countDownLatch.countDown();
},CountryEnum.forEach_CountryEnum(i).getRetMessage()).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName()+" ***秦帝国一统华夏");
}
public static void closeDoor() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i <= 6; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " 上完自学,离开教室");
countDownLatch.countDown();//减1
}, String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName() + " ****最后离开,关门");
}
}
枚举:
import lombok.Getter;
public enum CountryEnum {
ONE(1," 齐"),
TWO(2,"楚"),
THREE(3,"燕"),
FOUR(4,"赵"),
FIVE(5,"魏"),
SIX(6,"韩");
@Getter private Integer retCode;
@Getter private String retMessage;
CountryEnum(Integer retCode, String retMessage) {
this.retCode = retCode;
this.retMessage = retMessage;
}
public static CountryEnum forEach_CountryEnum(int index){
CountryEnum[] myArray= CountryEnum.values();
for(CountryEnum element: myArray){
if(index==element.getRetCode()){
return element;
}
}
return null;
}
}
CountDownLatch 作用:让一些线程阻塞,直到另一个线程完成一系列操作后才被唤醒
CountDownLatch 主要有两个方法,当一个活多个线程调用await方法时,调用线程会被阻塞。其他线程调用coutDown方法会将技术器减1(调用countDown方法的线程不会阻塞),
当计数器的值变为0时,因为调用await方法被阻塞的线程会被唤醒,继续执行.