CountDownLatch类+枚举类的应用

本文详细介绍了Java并发包中CountDownLatch的使用方法及其在多线程环境下的应用场景。通过实例展示了如何利用CountDownLatch来实现线程间的等待和通知机制,确保主线程在所有子线程完成任务后继续执行。

1、CountDownLatch介绍:

CountDownLatch:让一些线程阻塞直到另一些线程完成一系列操作后才被唤醒。
CountDownLatch主要有两个方法,当一个或多个线程调用await方法时,调用线程会被阻塞。其它线程调用countDown方法会将计数器减1(调用countDown方法的线程不会阻塞),当计数器的值变为零时,因调用await方法被阻塞的线程会被唤醒,继续执行。

2、CountDownLatch应用:

import java.util.concurrent.CountDownLatch;

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()+"\t 国被灭了...");
                countDownLatch.countDown();
            },CountryEnum.foreach_Enum(i).getName()).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"\t 秦国一统天下!");
    }
    public static void closeDoor() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName()+"\t 同学出门了!");
                countDownLatch.countDown();
            },"t"+String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"\t 班长最后关门走人...");
    }
}

3、枚举类应用:

public enum  CountryEnum {

    //可以相当于一个数据库
    ONE(1,"燕"),TWO(2,"赵"),THREE(3,"韩"),FOUT(4,"魏"),FIVE(5,"楚"),SIX(6,"齐");

    private Integer id;
    private String name;

    public static CountryEnum foreach_Enum(int index){
        CountryEnum[] enums = CountryEnum.values();
        for (CountryEnum anEnum : enums) {
            if(index == anEnum.getId()){
                return anEnum;
            }
        }
        return null;
    }

    CountryEnum(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    CountryEnum() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值