CountDownLatch 是 Java.util.concurrent 包中的一个类,用于在多个线程之间进行同步操作。它的作用是使一个线程等待其他线程完成一定数量的操作后再继续执行。

CountDownLatch 使用一个计数器来实现,这个计数器的初始值可以设置为大于 0 的任意整数。当一个线程完成了一定数量的操作后,可以调用 CountDownLatch 的 countDown() 方法来减少计数器的值。其他等待的线程可以调用 await() 方法来阻塞等待,直到计数器的值变为 0,才能继续执行。

CountDownLatch 通常用于一些需要等待其他线程完成某个任务后才能继续执行的场景,比如并发测试中所有线程都完成了指定的操作后再进行下一步操作,或者主线程等待子线程完成任务后再进行下一步操作等。

下面是一个简单的示例代码,演示了 CountDownLatch 的使用:

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3); // 设置计数器的初始值为 3

        // 创建三个线程
        Thread t1 = new Thread(() -> {
            System.out.println("Thread 1 is running");
            latch.countDown(); // 线程 1 完成了一个操作,计数器减 1
        });

        Thread t2 = new Thread(() -> {
            System.out.println("Thread 2 is running");
            latch.countDown(); // 线程 2 完成了一个操作,计数器减 1
        });

        Thread t3 = new Thread(() -> {
            System.out.println("Thread 3 is running");
            latch.countDown(); // 线程 3 完成了一个操作,计数器减 1
        });

        // 启动三个线程
        t1.start();
        t2.start();
        t3.start();

        latch.await(); // 等待计数器变为 0

        System.out.println("All threads have completed"); // 所有线程都完成了操作,继续执行
    }
}

运行上述代码,输出结果为:

Thread 1 is running
Thread 2 is running
Thread 3 is running
All threads have completed

可以看到,三个线程分别完成了一个操作后,计数器的值变为 0,主线程才能继续执行

CountDownLatch 的作用和使用

原文地址: http://www.cveoy.top/t/topic/iJ4V 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录