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()+"\t 國,被滅");
countDownLatch.countDown();
},CountryEnum.forEach_CountryEnum(i).getRetMessage()).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName()+"\t***秦帝國一統華夏");
}
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() + "\t上完自學,離開教室");
countDownLatch.countDown();//減1
}, String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName() + "\t****最後離開,關門");
}
}
枚舉:
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方法被阻塞的線程會被喚醒,繼續執行.