当涉及到并发编程时,CountDownLatch 是一个非常有用的工具。它提供了一种同步多个线程的方法,使得主线程能够等待其他线程完成它们的工作。
CountDownLatch 类位于 java.util.concurrent
包中,可以通过以下方式导入:
import java.util.concurrent.CountDownLatch;
CountDownLatch 的基本用法是在构造函数中传入一个整数,该整数表示需要等待完成的线程数。每个线程在完成任务之后,可以通过调用 countDown()
方法来通知 CountDownLatch 一个线程已经完成了。
主线程可以调用 await()
方法来阻塞,直到计数器归零。当计数器为零时,主线程将继续执行。
下面是一个示例代码,展示了 CountDownLatch 的使用:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) {
// 创建一个 CountDownLatch 实例,传入需要等待完成的线程数
CountDownLatch latch = new CountDownLatch(3);
// 创建三个工作线程,并将 CountDownLatch 实例传递给它们
WorkerThread worker1 = new WorkerThread(latch, "Worker 1");
WorkerThread worker2 = new WorkerThread(latch, "Worker 2");
WorkerThread worker3 = new WorkerThread(latch, "Worker 3");
// 启动工作线程
worker1.start();
worker2.start();
worker3.start();
try {
// 主线程等待所有工作线程完成
latch.await();
System.out.println("All workers have completed their tasks.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class WorkerThread extends Thread {
private final CountDownLatch latch;
public WorkerThread(CountDownLatch latch, String name) {
super(name);
this.latch = latch;
}
@Override
public void run() {
// 模拟线程执行任务
try {
Thread.sleep(2000);
System.out.println(getName() + " has completed its task.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 完成任务后调用 countDown() 方法
latch.countDown();
}
}
}
**
在这个示例中,我们创建了一个 CountDownLatch 实例,其计数器初始值为 3,然后创建了三个工作线程并传入该实例。每个工作线程模拟执行任务,然后调用 countDown()
方法,表示工作已完成。
主线程调用 latch.await()
方法来等待所有工作线程完成。当计数器减至零时,主线程将继续执行。
这就是 CountDownLatch 的基本用法。它可以用于等待多个线程的结果,或者等待某个条件满足后再继续执行。希望这篇文章对你有所帮助!