CountDownLatch类+枚举类的应用
程序员文章站
2022-03-04 14:24:27
...
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;
}
}