CountDownLatch怎么使用
时间: 2024-03-22 15:36:04 浏览: 60
CountDownLatch源码解析之countDown()
CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程执行完后再执行。下面是CountDownLatch的使用方法[^1]:
1. 初始化CountDownLatch对象,设置计数器的初始值为n。
```java
CountDownLatch latch = new CountDownLatch(n);
```
2. 在需要等待的线程中调用await()方法,使线程进入等待状态,直到计数器的值变为0。
```java
latch.await();
```
3. 在其他线程中执行完需要等待的任务后,调用countDown()方法,将计数器的值减1。
```java
latch.countDown();
```
4. 当计数器的值变为0时,await()方法返回,等待的线程继续执行。
下面是一个示例,演示了CountDownLatch的使用:
```java
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int n = 3;
CountDownLatch latch = new CountDownLatch(n);
// 创建并启动n个线程
for (int i = 0; i < n; i++) {
Thread thread = new Thread(new Worker(latch));
thread.start();
}
// 主线程等待所有线程执行完毕
latch.await();
System.out.println("All workers have finished their tasks.");
}
static class Worker implements Runnable {
private final CountDownLatch latch;
public Worker(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
// 模拟任务执行
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Worker finished its task.");
// 任务执行完毕后调用countDown()
latch.countDown();
}
}
}
```
这个示例中,主线程创建并启动了3个Worker线程,每个Worker线程模拟执行一个任务。主线程调用await()方法等待所有Worker线程执行完毕,当所有Worker线程都调用了countDown()方法后,主线程继续执行,输出"All workers have finished their tasks"。
阅读全文