天天看点

JAVA枚举类和CountDownLatch的应用!!

枚举类:相当于一个“小型数据库”。

CountDownLatch:是一个非常实用的多线程控制工具类。当一个或多个线程调用await方法时,调用线程会被阻塞。其他线程调用countDown方法会将计数器减一(调用countDown方法的线程不会阻塞),当计数器的值为零时,因调用await方法被阻塞的线程会被唤醒,继续执行。

类中主要的方法:

  • countDown() // 计数减一。
  • await() //等待,当计数减到0时,所有线程并行执行。

小DEMO:

public class CountDownLatchDemo {

    public static void main(String[] args) throws Exception {

        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() + "======秦   一统天下=======");

    }

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

    private Integer retCode;
    private String retmessage;

    public static CountryEnum forEach_CountryEnum(int index) {

        CountryEnum[] myArray = CountryEnum.values();

        for (CountryEnum element : myArray) {
            if (index == element.getRetCode()) {
                return element;
            }
        }
        return null;
    }

    public Integer getRetCode() {
        return retCode;
    }

    public String getRetmessage() {
        return retmessage;
    }

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

、、、

运行结果:

JAVA枚举类和CountDownLatch的应用!!