CountDownLatch

CountDownLatch

CountDownLatch

​ 需要一个线程等待所有线程执行完后,它再执行,这样的场景我们可以使用它。

有两个方法

countDownLatch.countDown(); 将count--;

countDownLatch.await(); 阻塞当前线程,直到count为0;

/*
    秦灭六国, 秦统一华夏
 */    
public class juc3 {


    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.getCountry(i).getRetMsg()).start();  //有可能传入的 i 不存在 有空指针风险 
        }

        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"秦朝一统天下~~~");

    }

}


---------------------------------------------------------------------------------------------------------------------
/*
    写个枚举类 
*/
public enum CountryEnum{
    one(1,"赵"),
    two(2,"齐"),
    three(3,"楚"),
    four(4,"燕"),
    five(5,"魏"),
    six(6,"韩")
    ;
    private Integer retCode;
    private String retMsg;

    public Integer getRetCode() {
        return retCode;
    }

    public String getRetMsg() {
        return retMsg;
    }

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

    public static CountryEnum getCountry(int retCode){

        //枚举类 有一个 values() 方法可以遍历所有枚举
        CountryEnum[] values = CountryEnum.values();

        for (CountryEnum value : values) {
            if (retCode == value.retCode){
                return value;
            }
        }
        return null;
    }
}

使用枚举类原因?

假设我们需要灭的不是6国,而是成百上千的国家,那我们怎么样实现 每次的 i 与国家名对应呢?

使用 switch case可以解决,但是没来一个线程就比较所有的条件,这显然很浪费时间效率。

再者,当我们需要灭的国家更改的时候,那我们还需要改这个代码。

如果,我们使用枚举类来实现这个 遍历的 i 与国家名称的记录的话,是不是会方便很多?(枚举类可以看成是一

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务