租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

JAVA中CountDownLatch如何使用

发布时间:2023-09-13 08:07:02

JAVA中CountDownLatch如何使用

在Java中,CountDownLatch是一个同步辅助类,它可让一个或多个线程等待其他线程完成操作后再继续履行。CountDownLatch可以用于以下场景:
1. 主线程等待多个子线程完成后再履行。
2. 多个子线程等待主线程完成某个任务后再开始履行。
CountDownLatch的使用步骤以下:
1. 创建一个CountDownLatch对象,指定需要等待的线程数量。
2. 在需要等待的线程中,调用CountDownLatch的await()方法,使线程进入等待状态,直到计数器减为0。
3. 在其他线程履行完需要等待的任务后,调用CountDownLatch的countDown()方法,将计数器减1。
4. 如果主线程需要等待其他线程完成后再履行,可以在主线程中调用CountDownLatch的await()方法,使主线程进入等待状态。
5. 当计数器减到0时,所有等待的线程将被唤醒,继续履行。
下面是一个简单的示例代码:
```java
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) {
int threadCount = 5;
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
Thread thread = new Thread(new WorkerThread(latch));
thread.start();
}
try {
latch.await(); // 主线程等待所有子线程履行终了
System.out.println("All threads have finished.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class WorkerThread implements Runnable {
private CountDownLatch latch;
public WorkerThread(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
// 履行需要等待的任务
System.out.println("Thread " + Thread.currentThread().getName() + " is running.");
// 任务履行终了后,调用countDown()方法将计数器减1
latch.countDown();
}
}
```
在上面的示例代码中,主线程创建了5个WorkerThread线程,并将CountDownLatch对象作为参数传递给它们。每一个WorkerThread线程履行完任务后,调用latch.countDown()方法将计数器减1。主线程调用latch.await()方法进入等待状态,直到计数器减为0,所有子线程履行完成。最后,主线程输出"All threads have finished."。