【枚举与countDownLatch的应用】

本文通过一个计数倒置锁(CountDownLatch)的Java示例,演示了如何使用该工具来同步等待多个任务完成后再继续执行主线程。具体实现了模拟六国灭亡后秦统一的故事场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、前言:

来源周阳面试第二季

main

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()+"国,被灭");
                countDownLatch.countDown();
            },CountryEnum.forEach_countryEnum(i).getRetMessage()).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"\t **********************秦帝国,一统华夏");
    }
}

枚举类

public enum  CountryEnum{
    ONE(1,"齐"),TWO(2,"楚"),THERE(3,"燕"),FOUR(4,"赵"),FIVE(5,"魏")
    ,SIX(6,"韩");

    private final Integer retCode;
    private final String retMessage;

    CountryEnum(Integer retCode, String retMessage) {
        this.retCode = retCode;
        this.retMessage = retMessage;
    }

    public Integer getRetCode() {
        return retCode;
    }

    public String getRetMessage() {
        return retMessage;
    }

    public static CountryEnum forEach_countryEnum(int index){
        CountryEnum[] values = CountryEnum.values();
        for (CountryEnum value : values) {
            if (index==value.retCode){
                return value;
            }
        }
        return null;
    }
}

执行结果:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值