CountDownLatch 枚举类 秦灭六国 统一

本文通过CountDownLatch实现了一个秦灭六国的多线程示例,展示了如何使用并发控制让主线程在所有子线程完成后执行。通过CountDownLatch的await()方法确保了顺序执行。


import java.util.concurrent.CountDownLatch;

/**
 * 多线程完成之后,主线程才可以继续;倒计时
 * 例子:秦灭六国 统一
 */

public class CountDownLatchDemo {

 
    //秦灭六国 统一
    private static final int num = CountryEnum.values().length;
    CountDownLatch countDownLatch= new CountDownLatch(num);
    for (int i = 0; i < num; i++) {
        final int tem = i;
        Thread thread =  new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()  +"灭亡");
                countDownLatch.countDown();
            }
        });
        thread.setName(CountryEnum.foreach_CountryEnum(i).getValue());
        thread.start();
    }
    countDownLatch.await();
    System.out.println("秦朝统一");

}
enum CountryEnum {
    ONE(1,"齐"),TWO(2,"楚"),THREE(3,"燕"),FOUR(4,"韩"),FIVE(5,"赵"),SIX(6,"魏");
    private int code;
    private String value;

    CountryEnum(int code,String value){
        this.code = code;
        this.value = value;
    }
    //枚举类遍历
    public static CountryEnum foreach_CountryEnum(int code){
        CountryEnum[] myArray = CountryEnum.values();
        for (CountryEnum countryEnum : myArray){
            if(code == countryEnum.getCode()){
                return countryEnum;
            }
        }
        return null;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值