CountDownLatch 示例
时间: 2023-11-12 07:59:03 浏览: 86
好的,这里是 CountDownLatch 的一个示例:
```java
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
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(() -> {
System.out.println("Thread started: " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread finished: " + Thread.currentThread().getName());
latch.countDown();
});
thread.start();
}
latch.await();
System.out.println("All threads finished.");
}
}
```
这个示例创建了 5 个线程,每个线程都会打印出自己的名字,并且在执行完一些操作后调用 `countDown()` 方法。主线程调用 `await()` 方法等待所有线程执行完毕后输出 "All threads finished."。
阅读全文
相关推荐
















