zoukankan      html  css  js  c++  java
  • 【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,但是使用多线程进行输出,最后的“一年过去了...”的输出,可能随机穿插在四季的中间。

  • 相关阅读:
    对vue中nextTick()的理解及使用场景说明
    微信小程序的视图与渲染
    1分钟了解微信小程
    Idea搭建Spring+SpringMvc+Mybatis框架集成项目
    idea 新建不了servlet文件 方法(1)
    idea使用大全(加载mysql驱动)
    开发文档规范
    如何架构一个框架
    mac os x
    mongodb rockmongo
  • 原文地址:https://www.cnblogs.com/xdcat/p/12957206.html
Copyright © 2011-2022 走看看