Java CountDownLatch的用法
时间: 2024-04-29 12:18:32 浏览: 155
Java中的CountDownLatch是一种同步工具,它可以让一个线程等待其他线程完成操作后再执行。具体来说,CountDownLatch会在初始化时指定一个计数器,当其他线程调用其countDown()方法时,该计数器会减1,当计数器减到0时,那些等待的线程就会被唤醒,继续执行。
下面给出一个使用CountDownLatch的例子,其中主线程等待两个子线程执行完成后再输出一句话:
```java
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(2);
new Thread(() -> {
try {
Thread.sleep(1000L);
System.out.println("Thread 1 finished");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
}).start();
new Thread(() -> {
try {
Thread.sleep(2000L);
System.out.println("Thread 2 finished");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
}).start();
countDownLatch.await();
System.out.println("All threads finished");
}
}
```
输出结果为:
```
Thread 1 finished
Thread 2 finished
All threads finished
```
上面的代码中,我们首先创建了一个CountDownLatch对象并将计数器设为2,然后启动了两个线程执行一些操作,并在操作完成后调用countDown()方法减少计数器。最后在主线程中调用await()方法等待计数器归零后继续执行。
阅读全文