CountDownLatch和枚举配合使用

网友投稿 649 2022-08-31

CountDownLatch和枚举配合使用

CountDownLatch和枚举配合使用

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****最后离开,关门"); }}

枚举:

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; }}

CountDownLatch 作用:让一些线程阻塞,直到另一个线程完成一系列操作后才被唤醒

CountDownLatch 主要有两个方法,当一个活多个线程调用await方法时,调用线程会被阻塞。其他线程调用coutDown方法会将技术器减1(调用countDown方法的线程不会阻塞),当计数器的值变为0时,因为调用await方法被阻塞的线程会被唤醒,继续执行.

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:DDD领域模型AutoMapper实现DTO(七)
下一篇:关于go语言中gc的初步研究(gcam go)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~