CountDownLatch和枚举配合使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.concurrent.CountDownLatch;
 
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()+"\t***秦帝国一统华夏");
    }
 
    public static void closeDoor() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 0; i <= 6; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "\t上完自学,离开教室");
                countDownLatch.countDown();//减1
            }, String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + "\t****最后离开,关门");
    }
}

  枚举:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import lombok.Getter;
 
public enum CountryEnum {
    ONE(1," 齐"),
    TWO(2,"楚"),
    THREE(3,"燕"),
    FOUR(4,"赵"),
    FIVE(5,"魏"),
    SIX(6,"韩");
 
    @Getter private Integer retCode;
    @Getter private String retMessage;
 
    CountryEnum(Integer retCode, String retMessage) {
        this.retCode = retCode;
        this.retMessage = retMessage;
    }
 
    public static CountryEnum forEach_CountryEnum(int index){
        CountryEnum[] myArray= CountryEnum.values();
        for(CountryEnum element: myArray){
            if(index==element.getRetCode()){
                return element;
            }
        }
        return null;
    }
}

  

1
CountDownLatch 作用:让一些线程阻塞,直到另一个线程完成一系列操作后才被唤醒
1
CountDownLatch 主要有两个方法,当一个活多个线程调用await方法时,调用线程会被阻塞。其他线程调用coutDown方法会将技术器减1(调用countDown方法的线程不会阻塞),<br>当计数器的值变为0时,因为调用await方法被阻塞的线程会被唤醒,继续执行.<br><br>
posted @   石shi  阅读(161)  评论(0编辑  收藏  举报
编辑推荐:
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
阅读排行:
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(三):用.NET IoT库
· 【非技术】说说2024年我都干了些啥
历史上的今天:
2018-03-16 SQLServer索引及统计信息
2017-03-16 SqlServer中查看索引的使用情况
点击右上角即可分享
微信分享提示