CountDownLatch,countDown
时间: 2024-12-27 21:21:43 浏览: 5
### CountDownLatch 的 `countDown` 方法详解
#### 计数值减少机制
每当调用一次 `countDown()` 方法,内部计数器会减一。当计数器达到零时,在此之前因调用了 `await()` 而阻塞的线程将会被唤醒并继续执行[^3]。
#### 代码示例
下面是一个简单的例子来展示如何使用 `countDown()`:
```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 = 0; i < numberOfThreads; ++i) {
Thread worker = new Worker(latch);
worker.start();
}
System.out.println("Waiting for all threads to finish...");
latch.await(); // 主线程在此处等待其他线程完成工作
System.out.println("All tasks are done.");
}
}
class Worker extends Thread {
private final CountDownLatch latch;
public Worker(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
doWork();
latch.countDown(); // 工作者线程完成任务后调用 countDown()
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void doWork() throws InterruptedException {
// Simulate work being done by sleeping.
Thread.sleep((long)(Math.random() * 1000));
}
}
```
在这个例子中,主线程创建了一个具有指定数量的工作线程,并给每个分配相同的倒计时锁存器实例。每个工作者线程在其任务完成后都会调用 `latch.countDown()` 来通知它已完成其部分的任务。一旦所有的工作者都完成了它们各自的任务并将计数降至零,则主线程将继续向前推进[^2]。
阅读全文