CountDownLatch的 常用场景及使用示例
CountDownLatch
是Java并发编程中一个非常实用的同步工具类,它允许一个或多个线程等待其他线程完成操作后再继续执行。其核心功能在于控制线程的执行流程,确保某些关键操作或准备工作完全就绪后,再释放等待的线程继续执行。以下是一些CountDownLatch
的常用场景及一个简单的使用示例:
常用场景
- 应用启动时的初始化: 在应用程序启动时,可能需要等待多个初始化任务完成(如数据库连接、配置加载等)后,才允许处理客户端请求。
- 并行任务的同步: 当一个任务需要等待多个并行执行的任务全部完成才能继续时,可以使用
CountDownLatch
。 - 测试高并发场景: 在模拟高并发测试时,可以控制多个线程同时开始执行,以测试系统在高负载下的表现。
使用示例
以下是一个简单的使用CountDownLatch
的例子,展示了如何让主线程等待若干个子线程全部完成后再继续执行:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int threadCount = 5;
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; ++i) {
Runnable worker = new WorkerThread(latch, "Worker-" + i);
executorService.execute(worker);
}
System.out.println("Main thread is waiting for all workers to complete their tasks...");
latch.await(); // 主线程在此等待,直到计数器变为0
System.out.println("All workers have completed their tasks. Main thread is now continuing.");
executorService.shutdown();
}
}
class WorkerThread implements Runnable {
private final CountDownLatch latch;
private final String name;
WorkerThread(CountDownLatch latch, String name) {
this.latch = latch;
this.name = name;
}
@Override
public void run() {
try {
Thread.sleep(1000); // 模拟执行任务
System.out.println(name + " has finished the task.");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
latch.countDown(); // 完成任务后计数减一
}
}
}
在这个例子中,我们创建了一个固定大小的线程池来执行5个WorkerThread
任务。每个工作线程完成自己的任务后会调用latch.countDown()
减少计数器的值。主线程则通过调用latch.await()
等待,直到所有的工作线程都完成了它们的任务(即计数器变为0),之后主线程才会继续执行。