CountDownLatch类详解

在 Java 中,CountDownLatch 是一个同步辅助类,它允许一个或多个线程等待其他线程完成操作。CountDownLatch 的构造函数接受一个参数,这个参数指定了需要等待的计数。当计数到达零时,所有等待的线程将继续执行。

private final static CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(threadCount);

这行代码创建了一个 CountDownLatch 实例,名为 COUNT_DOWN_LATCH。这个实例被初始化为 threadCount,这意味着在所有线程都完成它们的任务之前,任何线程调用 COUNT_DOWN_LATCH.await() 方法时都会阻塞。一旦 threadCount 个线程都完成了它们的任务,并且每个线程都调用了 COUNT_DOWN_LATCH.countDown() 方法,计数就会减少,直到计数达到零,此时所有等待的线程都会被唤醒并继续执行。

这里的 threadCount 应该是一个表示线程数量的变量。COUNT_DOWN_LATCH 被声明为 privatefinal,以及 static,这意味着它是一个类的私有静态成员,一旦初始化后就不能被修改,且在类的所有实例之间共享。

使用场景

CountDownLatch 通常用于以下场景:

  1. 一次性任务:当一个任务需要在多个线程完成它们的部分工作后才能继续执行时。

  2. 初始化:在应用程序启动时,可能需要初始化多个资源,只有在所有资源都初始化完成后,应用程序才能继续运行。

  3. 关闭操作:在应用程序关闭时,可能需要等待多个清理操作完成。

示例

下面是一个简单的示例,展示了如何使用 CountDownLatch

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    private static final CountDownLatch latch = new CountDownLatch(2);

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            System.out.println("Thread 1 is starting");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println("Thread 1 is finishing");
            latch.countDown();
        });

        Thread t2 = new Thread(() -> {
            System.out.println("Thread 2 is starting");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println("Thread 2 is finishing");
            latch.countDown();
        });

        t1.start();
        t2.start();

        System.out.println("Main thread is waiting for other threads to finish");
        latch.await();
        System.out.println("All threads have finished");
    }
}

 在这个示例中,主线程将等待两个工作线程完成它们的任务。每个工作线程在完成时都会调用 countDown() 方法,当计数达到零时,主线程将继续执行。

代码执行顺序的详细流程

  1. 主线程main 方法):

    • 创建 CountDownLatch

    • 创建并启动线程 t1 和 t2

    • 打印 "Main thread is waiting for other threads to finish"

    • 调用 latch.await(),进入等待状态。

  2. 线程 t1

    • 打印 "Thread 1 is starting"

    • 休眠 1 秒。

    • 打印 "Thread 1 is finishing"

    • 调用 latch.countDown()

  3. 线程 t2

    • 打印 "Thread 2 is starting"

    • 休眠 1 秒。

    • 打印 "Thread 2 is finishing"

    • 调用 latch.countDown()

  4. 主线程

    • 当 latch 的计数器减到 0 时,主线程从 latch.await() 返回。

    • 打印 "All threads have finished"

 输出结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值