CountDownLatch如何使用
时间: 2025-04-04 08:03:25 浏览: 25
`CountDownLatch` 是 Java 并发包 (`java.util.concurrent`) 提供的一种同步工具类,用于让一个或多个线程等待其他线程完成操作后再继续执行。它通过计数器(count)来进行控制,当计数器减至零时,所有因等待而阻塞的线程会被唤醒并继续运行。
---
### 核心功能
1. **初始化**:通过构造函数设置初始值 (即需要等待的任务数量)。
2. **倒计时**:每个任务完成后调用 `countDown()` 方法使计数器递减。
3. **等待结束**:主线程或其他线程可以调用 `await()` 或带超时时间的 `await(long timeout, TimeUnit unit)` 方法来等待直到计数值归零。
一旦计数到达零之后,再对 latch 进行额外 countdown 操作不会引发异常也无效;此外已经开启通行状态后的 await 呼叫会立即返回不再有任何延迟效果。
---
### 示例代码
下面的例子展示了如何使用 `CountDownLatch` 让主程序等待若干个子线程全部执行完毕才退出:
```java
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int numberOfThreads = 3;
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for(int i=1;i<=numberOfThreads ;i++) {
Thread worker = new WorkerThread(latch,"Worker-"+i);
worker.start();
}
System.out.println("Waiting for all threads to finish...");
// 主线程在此处等待,直至所有工作线程完成其任务
latch.await();
System.out.println("All tasks completed.");
}
}
class WorkerThread extends Thread{
private final CountDownLatch latch;
public WorkerThread(CountDownLatch latch,String name){
super(name);
this.latch=latch;
}
@Override
public void run(){
try{
// Simulate task processing time.
sleep((long)(Math.random()*1000));
System.out.println(Thread.currentThread().getName()+" finished.");
}finally{
// Signal that we're done with our work so the count can be decremented by one.
latch.countDown();
}
}
}
```
---
### 输出示例
```
Waiting for all threads to finish...
Worker-1 finished.
Worker-2 finished.
Worker-3 finished.
All tasks completed.
```
在这个例子中,我们创建了三个工作者线程并且设置了相应的倒计时锁存器实例。主线程在开始的时候打印了一条消息表示正在等待所有的子线程都完成了它们的工作,在每一个子线程结束了它的模拟计算后都会去通知一次这个锁存器对象减少他的内部计数器数值,最后当所有的子线程都已经成功地告知他们已完成各自的职责之时,则原来处于挂起状态下的main thread 就得以恢复正常的运作轨迹并显示出最终的消息表明一切皆已就绪。
---
###
阅读全文
相关推荐















