请用java的CountDownLatch帮我写一个例子
时间: 2023-11-16 15:01:46 浏览: 82
java并发工具类
以下是一个使用Java的CountDownLatch的例子:
```java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int numThreads = 5;
CountDownLatch latch = new CountDownLatch(numThreads);
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
for (int i = 0; i < numThreads; i++) {
executor.execute(() -> {
try {
// 模拟线程执行任务
Thread.sleep((long) (Math.random() * 1000));
System.out.println("Thread " + Thread.currentThread().getId() + " finished task.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
});
}
// 等待所有线程执行完毕
latch.await();
System.out.println("All threads finished tasks.");
executor.shutdown();
}
}
```
这个例子创建了一个有5个线程的线程池,每个线程执行一个随机时间的任务,最后等待所有线程执行完毕后输出一条消息。在这个例子中,CountDownLatch被用来等待所有线程执行完毕。每个线程执行完毕后都会调用`countDown()`方法,表示一个线程已经完成了任务。主线程调用`await()`方法等待所有线程执行完毕,当所有线程都完成任务后,主线程才会继续执行。
阅读全文