枚举类与CountDownLatch 的小练习

枚举类小练习


秦国扫六合
CountDownLatch 是允许一个或多个线程等待直到在其他线程中执行的一组操作完成的同步辅助。 CountDownLatch用给定的计数初始化。 await方法阻塞,直到由于 countDown()方法的调用而导致当前计数达到零,之后所有等待线程被释放,并且任何后续的await 调用立即返回。 这是一个一次性的现象 - 计数无法重置。

public enum  CountryEnum {
    ONE(1,"齐"),TWO(2,"燕"),THREE(3,"赵"),FOUR(4,"韩"),FIVE(5,"魏"),SIX(6,"楚");
    private Integer num;
    private String nation;

    public static CountryEnum foreach(int num){
        CountryEnum[] values = CountryEnum.values();
        for (CountryEnum element:values) {
            if(num == element.getNum()){
                return element;
            }
        }
        return null;
    }

    CountryEnum() {
    }

    CountryEnum(Integer num, String nation) {
        this.num = num;
        this.nation = nation;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    public String getNation() {
        return nation;
    }

    public void setNation(String nation) {
        this.nation = nation;
    }
}

利用CountDownLatch,多线程执行

public class CountDownLatchDemo {
    public static void main(String[] args) {
        CountDownLatch count = new CountDownLatch(6);

        for (int i = 1; i <= 6; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"\t"+"国被灭");
                count.countDown();
                //此处foreach为枚举类中的方法
            },CountryEnum.foreach(i).getNation()).start();
        }
        try {
            count.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"\t"+"秦国统一中原");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值