Java中枚举在生产中的常见用法

首先枚举的入门请参考博客 java枚举入门

最近在学习JUC中的countdownlatch时做练习Java并发之CountDownLatch、CyclicBarrier、Semaphore使用实例,用到枚举,需要六个国家。代码如下:

枚举


/**
 * 枚举 枚举在生产中的使用
 */
public enum CountryEnum {

    One("齐", 1), two("楚", 2),
    three("燕", 3), four("韩", 4), five("赵", 5), six("魏", 6);

    @Getter
    private String retMessage;
    @Getter
    private int retCode;

    CountryEnum(String message, int code) {
        this.retCode = code;
        this.retMessage = message;
    }

    public static CountryEnum forEach_CountryEnum(int index) {
        CountryEnum[] enums = CountryEnum.values();
        for (CountryEnum countryEnum : enums) {
            if (countryEnum.getRetCode() == index) {
                return countryEnum;
            }
        }
        return null;
    }
}

使用

/**
 * @ClassName: CountDownLatchDemo
 * @description:
 * @author: XZQ
 * @create: 2020/2/28 8:27
 **/
public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
        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 六国灭");                //System.out.println(CountryEnum.SIX);        //System.out.println(CountryEnum.SIX.getRetCode());        //System.out.println(CountryEnum.SIX.getRetMessage());     }

    }
}
发布了38 篇原创文章 · 获赞 4 · 访问量 3183

猜你喜欢

转载自blog.csdn.net/qq_42107430/article/details/104550078