把这段代码用java写出来
时间: 2024-03-22 14:39:36 浏览: 18
好的,以下是一个简单的使用 CountDownLatch 的 Java 代码示例:
```java
import java.util.concurrent.CountDownLatch;
public class Example {
public static void main(String[] args) throws InterruptedException {
int numThreads = 5;
CountDownLatch latch = new CountDownLatch(numThreads);
for (int i = 0; i < numThreads; i++) {
Thread thread = new Thread(new WorkerThread(latch));
thread.start();
}
latch.await();
System.out.println("All worker threads have finished.");
}
static class WorkerThread implements Runnable {
private final CountDownLatch latch;
public WorkerThread(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
System.out.println("Worker thread is performing some work...");
// 模拟线程执行一段任务
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Worker thread has finished its work.");
latch.countDown();
}
}
}
```
在上述示例中,我们使用 CountDownLatch 来等待 5 个线程执行完毕后再继续往下执行。在主线程中,我们创建了 5 个 WorkerThread 对象,每个对象都持有同一个 CountDownLatch 实例。在每个 WorkerThread 线程中,我们执行一段模拟的任务,并在任务完成后调用 countDown() 方法来通知 CountDownLatch 计数器减 1。在主线程中,我们调用 await() 方法来等待计数器归零,此时所有的 WorkerThread 线程都已经执行完毕。最后,我们输出一条消息来表示所有线程都已经完成了任务。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)