【JUC】CountDownLatch和Java枚举的使用例子

public enum CountryEnum {
    ONE(1,"春"),
    TWO(2,"夏"),
    THREE(3,"秋"),
    FOUR(4,"冬");

    private Integer retCode;
    private String reMessage;

    CountryEnum(int retCode, String reMessage) {
        this.retCode = retCode;
        this.reMessage = reMessage;
    }

    public String getReMessage() {
        return reMessage;
    }

    public Integer getRetCode() {
        return retCode;
    }

    public static CountryEnum forEachCountryEnum(int index){
        CountryEnum[] values = CountryEnum.values();
        for(CountryEnum value: values){
            if(index == value.getRetCode()){
                return value;
            }
        }
        System.out.println("not find " + index);
        return null;
    }
}

 

 1 public class TestDemo {
 2     public static void main(String[] args) throws InterruptedException {
 3         CountDownLatch countDownLatch = new CountDownLatch(4);
 4         for (int i = 1; i <= 4; i++) {
 5             new Thread(()->{
 6                 System.out.println(Thread.currentThread().getName()+"天来了......");
 7                 countDownLatch.countDown();//countDownLatch减一个
 8             }, CountryEnum.forEachCountryEnum(i).getReMessage()).start();
 9         }
10         countDownLatch.await();//只有countDownLatch等于0才执行下一个线程(main线程)
11         System.out.println("一年过去了...");
12     }
13 }

 输出信息:如果没有使用CountDownLatch,但是使用多线程进行输出,最后的“一年过去了...”的输出,可能随机穿插在四季的中间。

 

posted @ 2020-05-25 15:30  xd会飞的猫  阅读(192)  评论(0编辑  收藏  举报