JAVA 多线程编程之CountDownLatch
时间: 2023-11-16 17:55:34 浏览: 121
java并发编程中CountDownLatch和CyclicBarrier的使用.pdf
CountDownLatch是Java中的一个同步工具类,它可以让一个或多个线程等待其他线程完成操作后再执行。CountDownLatch内部维护了一个计数器,初始值为线程数,每个线程完成任务后会将计数器减1,当计数器为0时,等待的线程就会被唤醒。
下面是一个简单的例子,其中有5个线程需要完成任务后主线程才能继续执行:
```java
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " is working");
latch.countDown();
}).start();
}
latch.await();
System.out.println("All threads have finished working");
}
}
```
输出结果为:
```
Thread-0 is working
Thread-1 is working
Thread-2 is working
Thread-3 is working
Thread-4 is working
All threads have finished working
```
在这个例子中,主线程调用了`latch.await()`方法,等待计数器变为0。每个线程完成任务后调用`latch.countDown()`方法,将计数器减1。当计数器变为0时,主线程被唤醒,继续执行。
阅读全文