CountDownLatch
CountDownLatch是Java多线程编程中的一个同步辅助类。它可以让一个或多个线程等待其他线程完成某个操作后再继续执行。
CountDownLatch内部维护一个计数器(count),并提供了两种基本操作:
-
countDown():将计数器减1。当某个线程完成了需要等待的操作时,调用countDown()方法,表示已经完成了一个任务。
-
await():阻塞调用此方法的线程,直到计数器的值变为0。当其他线程调用countDown()方法将计数器减至0时,await()方法返回,被阻塞的线程继续执行。
下面是一个简单的示例代码,说明如何使用CountDownLatch:
import java.util.concurrent.CountDownLatch;
public class Example {
public static void main(String[] args) throws InterruptedException {
int numThreads = 3;
CountDownLatch latch = new CountDownLatch(numThreads);
for (int i = 0; i < numThreads; i++) {
Thread thread = new Thread(new WorkerThread(latch));
thread.start();
}
latch.await(); // 等待所有线程完成任务
System.out.println("All tasks completed");
}
static class WorkerThread implements Runnable {
private CountDownLatch latch;
public WorkerThread(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
System.out.println("Thread executing task");
// 模拟耗时操作
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
latch.countDown(); // 完成任务,计数器减1
}
}
}
在上述示例中,我们创建了三个工作线程,并将每个线程的任务分配给一个CountDownLatch对象。每个工作线程执行任务后,都会调用countDown()方法,计数器减1。在主线程中,我们调用await()方法来等待计数器变为0,即等待所有工作线程完成任务。最后,当所有任务完成后,我们输出"All tasks completed"。
CountDownLatch常用于一些需要等待其他线程完成后才能继续执行的场景,例如主线程需要等待所有子线程完成某个并发任务后再进行下一步操作,或者协调多个线程的处理流程。