1.描述
CountDownLatch的出现解决不是偶然,也为了解决之前线程之间出现的一些问题
例如下面的代码案例:
public class CutDownLatchDemo {
public static void main(String[] args) throws Exception {
closeDoor();
}
public static void closeDoor() throws InterruptedException {
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName()+"\t 上完自习,离开教室走人");
}, String.valueOf(i)).start();
}
System.out.println(Thread.currentThread().getName()+"\t 88班长锁门,走人");
}
}
运行结果:
1 上完自习,离开教室走人
2 上完自习,离开教室走人
main 88班长锁门,走人
6 上完自习,离开教室走人
4 上完自习,离开教室走人
5 上完自习,离开教室走人
3 上完自习,离开教室走人
从运行结果可以看出,并不能保证顺序,我们期望的结果是,所有人都离开教室后,班长开始锁门,准备就绪 但结果同学没有完全离开班长就开始锁门显然不符合常理,为了解决这个问题CountDownLatch应运而生就像是火箭发射一样,前提都准备完之后在进行发射
2.改进后的代码
public class CutDownLatchDemo {
public static void main(String[] args) throws Exception {
closeDoor();
}
public static void closeDoor() throws InterruptedException {
CountDownLatch cutDown = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName()+"\t 上完自习,离开教室走人");
cutDown.countDown();
}, String.valueOf(i)).start();
}
cutDown.await();
System.out.println(Thread.currentThread().getName()+"\t 88班长锁门,走人");
}
}
运行结果:
1 上完自习,离开教室走人
3 上完自习,离开教室走人
5 上完自习,离开教室走人
2 上完自习,离开教室走人
6 上完自习,离开教室走人
4 上完自习,离开教室走人
main 88班长锁门,走人
可以看出,主线程main一直在再等待,直到其他线程执行完毕后在执行,从中很好的控制了线程的执行顺序
在开发过程中我们经常会遇到if-else判断,选项一多我们要写很多if-else代码看起来很臃肿,此时我们可以使用枚举,时代码变得简洁起来
package com.concurrent;
import lombok.Getter;
public enum CountryEnum {
ONE(1,"齐"), TWO(2,"楚"), THREE(3,"燕"), FOUR(4,"赵"), FIVE(5,"魏"), SIX(6,"韩");
@Getter private Integer resCode;
@Getter private String resMessage;
CountryEnum(Integer resCode, String resMessage) {
this.resCode = resCode;
this.resMessage = resMessage;
}
public static CountryEnum getCountryElement(int index){
CountryEnum [] countryEnumArr =CountryEnum.values();
for(CountryEnum element: countryEnumArr){
if(index == element.getResCode()){
return element;
}
}
return null;
}
}
public class CutDownLatchDemo {
public static void main(String[] args) throws Exception {
// closeDoor();
CountDownLatch cutDown = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName()+"\t 国在,被灭");
cutDown.countDown();
}, CountryEnum.getCountryElement(i).getResMessage()).start();
}
cutDown.await();
System.out.println(Thread.currentThread().getName()+"\t 秦灭六国,一统华夏");
}
}