本文目录:
CountDownLatch基本概念
CountDownLatch案例:6个同学陆续离开教室后班长才可以关门
CountDownLatch案例:秦灭6国,一统华夏
1. CountDownLatch基本概念
1. 让一些线程阻塞直到另一些线程完成一系列操作后才被唤醒。
2. CountDownLatch主要有两个方法,当一个或多个线程调用await方法时,这些线程会阻塞。其它线程调用countDown方法会将计数器减1(调用countDown方法的线程不会阻塞),当计数器的值变为0时,因await方法阻塞的线程会被唤醒,继续执行。
2. CountDownLatch案例:6个同学陆续离开教室后班长才可以关门
实现:
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();
},String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName()+"\t 班长关门走人");
}
}
编译结果
3. CountDownLatch案例:秦灭6国,一统华夏
六国我们用枚举模拟,具体代码如下:
public enum CountryEnums {
ONE(1,"韩"),TWO(2,"魏"),THREE(3,"赵"),FOUR(4,"齐"),FIVE(5,"楚"),SIX(6,"燕");
private Integer retCode;
private String retMessage;
CountryEnums(Integer retCode, String retMessage) {
this.retCode = retCode;
this.retMessage = retMessage;
}
public Integer getRetCode() {
return retCode;
}
public void setRetCode(Integer retCode) {
this.retCode = retCode;
}
public String getRetMessage() {
return retMessage;
}
public void setRetMessage(String retMessage) {
this.retMessage = retMessage;
}
public static CountryEnums forEachCountryEnums(Integer index){
for (CountryEnums element: values()) {
if (element.getRetCode() == index){
return element;
}
}
return null;
}
}
主体代码:
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();
},CountryEnums.forEachCountryEnums(i).getRetMessage()).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName()+"\t 秦,统一华夏");
System.out.println("------------------");
//枚举测试代码
System.out.println(CountryEnums.ONE);
System.out.println(CountryEnums.ONE.getRetCode());
System.out.println(CountryEnums.ONE.getRetMessage());
}
编译结果: