CountDownLatch内容解释
CountDownLatch只有带参数int n的构造器。表示从n开始至0倒计时,当Count为0时,则规定的操作才可以执行
使用场景
已知某个线程是用来做收尾工作的,只能等待其他前提线程都执行完时,这个收尾线程才能进行工作。
则在初始化countDownLatch对象时,传入其他线程数。在每个线程内部执行完后调用countDownLatch.countDown()方法实现一次计数。在收尾线程前一行执行countDownLatch.await()方法,表示当前线程等待计数归0再接着执行。
1.代码模拟5个线程需要出门,由最后一个线程进行锁门
锁门线程只能等待5个前提线程都出门后,才能开始执行
未使用CountDownLatch计数对象的代码Demo
public class CountDownLatchDemo {
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " 出门");
}, String.valueOf(i)).start();
}
System.out.println("看门员开始锁门");
}
}
从下面运行结果中可看出产生了严重的后果,此时看门员没有等待所有人都出门,就已经把门锁上了。
使用CountDownLatch对象来计数前提线程的已执行数量。
package lock;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
for(int i = 0; i < 5; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " 出门");
countDownLatch.countDown();
}, String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println("看门员开始锁门");
}
}
从运行结果可知,前提线程无序外出(执行),看门员在最后才进行锁门(执行)
2.代码模拟秦始皇灭六国而一统天下(必须六国灭亡,天下才能一统)
使用枚举类设置key、value
// 创建枚举类,给线程编号取名字
enum CountryEnum {
ONE(1, "齐"),TWO(2, "楚"),THREE(3, "燕"),FOUR(4, "韩"),FIVE(5, "赵"),SIX(6, "魏");
private Integer retCode;
private String retMessage;
CountryEnum(Integer retCode, String retMessage) {
this.retCode = retCode;
this.retMessage = retMessage;
}
public Integer getRetCode() {
return retCode;
}
public String getRetMessage() {
return retMessage;
}
// 遍历枚举
public static CountryEnum forEach_CountryEnum(int index) {
CountryEnum[] values = CountryEnum.values();
for (CountryEnum element : values) {
if (index == element.getRetCode()) {
return element;
}
}
return null;
}
}
主线程创建六个线程灭亡六国。由主线程统一全国
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() + " 国被灭亡了");
countDownLatch.countDown();
// 创建枚举类CountryEnum,传入key值,获得value,给线程取名
}, CountryEnum.forEach_CountryEnum(i).getRetMessage()).start();
}
countDownLatch.await();
System.out.println("秦始皇统一了天下");
}