in JUC kit package,CountDownLatch is a frequently-used class in specific concurrent sence,such as the last execution.
as we use countDownLatch's getCount() method to judge the last execution when to run.
the following code is to use CountDown Latch to solve the problem.
package JavaAdvanced;
import java.util.concurrent.CountDownLatch;
/**
* @author 韦海涛
* @version 1.0
* @date 4/5/2021 12:39 AM
*/
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(4);
for (int i = 0; i < 4; i++) {
final String temp = i+"";
new Thread(()->{
System.out.println("now is\t"+Thread.currentThread().getName()+"run");
countDownLatch.countDown();
},temp).start();
}
while (countDownLatch.getCount()!=0){
countDownLatch.await();
}
System.out.println(Thread.currentThread().getName()+" have run to zero");
}
}

if we need execute orderly.how to implement it?
package JavaAdvanced;
import java.util.concurrent.CountDownLatch;
/**
* @author 韦海涛
* @version 1.0
* @date 4/5/2021 12:39 AM
*/
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(4);
for (int i = 1; i <= 4; i++) {
final int temp = i;
new Thread(()->{
System.out.println("now is\t"+Thread.currentThread().getName()+"run");
countDownLatch.countDown();
},NumEnum.foreach_elemnt(temp).getMessage()).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName()+" have run to zero");
}
}
package JavaAdvanced;
/**
* @author 韦海涛
* @version 1.0
* @date 4/5/2021 1:11 AM
*/
public enum NumEnum {
ONE(1,"第1位同学"),
TWO(2,"第2位同学"),
THREE(3,"第3位同学"),
THIRD(4,"第4位同学");
private int id;
private String message;
NumEnum(int id,String message){
this.id = id;
this.message = message;
}
public static NumEnum foreach_elemnt(int index){
NumEnum[] myArray = NumEnum.values();
for(NumEnum numEnum:myArray){
if(numEnum.getId()==index){
return numEnum;
}
}
return null;
}
public int getId() {
return id;
}
public String getMessage() {
return message;
}
public void setId(int id) {
this.id = id;
}
public void setMessage(String message) {
this.message = message;
}
}

Java并发编程:CountDownLatch实现有序执行

本文介绍了如何在Java中使用CountDownLatch确保线程按顺序执行,通过示例展示了如何创建CountDownLatch实例并配合await()方法控制线程执行顺序。
1660

被折叠的 条评论
为什么被折叠?



