CountDownLatch也是一个java.util.concurrent包中的类,可以设置一个初始数值,在数值大于0之前让调用await()方法的线程堵塞住,数值为0是则会放开所有阻塞住的线程。底层基于AQS实现
CountDownLatch
是一个同步工具,它可以让一个或多个线程等待其他线程完成操作后再继续执行。其中使用 CountDownLatch
等待多个线程完成后再执行主线程:
代码示例:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public void performTask() throws InterruptedException {
int numThreads = 3;
CountDownLatch latch = new CountDownLatch(numThreads);
for (int i = 0; i < numThreads; i++) {
Thread thread = new WorkerThread(latch);
thread.start();
}
latch.await(); // 等待所有线程完成
System.out.println("All worker threads have completed.");
}
private static class WorkerThread extends Thread {
private CountDownLatch latch;
public WorkerThread(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
// 执行任务
latch.countDown(); // 任务完成后减少计数
}
}
}
https://blog.csdn.net/javanewber/article/details/132189657
https://cloud.tencent.com/developer/article/1786286