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

  • 相关阅读:
    【Python学习】读取Excel文件,并写入Excel
    异步编程
    LINQ入门
    [Leetcode Weekly Contest]207
    [Leetcode Weekly Contest]203
    VsCode插件,自动生成注释koroFileHeader
    vue样式穿透 ::v-deep的具体使用
    springcloud,springboot,springcloud-alibaba 之间版本关系
    sharding-sphere 单库分表实例
    CDN动态加速技术
  • 原文地址:https://www.cnblogs.com/xdcat/p/12957206.html
Copyright © 2011-2022 走看看