CountDownLatch的 常用场景及使用示例

CountDownLatch的 常用场景及使用示例

CountDownLatch是Java并发编程中一个非常实用的同步工具类,它允许一个或多个线程等待其他线程完成操作后再继续执行。其核心功能在于控制线程的执行流程,确保某些关键操作或准备工作完全就绪后,再释放等待的线程继续执行。以下是一些CountDownLatch的常用场景及一个简单的使用示例:

常用场景

  1. 应用启动时的初始化: 在应用程序启动时,可能需要等待多个初始化任务完成(如数据库连接、配置加载等)后,才允许处理客户端请求。
  2. 并行任务的同步: 当一个任务需要等待多个并行执行的任务全部完成才能继续时,可以使用CountDownLatch
  3. 测试高并发场景: 在模拟高并发测试时,可以控制多个线程同时开始执行,以测试系统在高负载下的表现。

使用示例

以下是一个简单的使用CountDownLatch的例子,展示了如何让主线程等待若干个子线程全部完成后再继续执行:

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        int threadCount = 5;
        ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
        CountDownLatch latch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; ++i) {
            Runnable worker = new WorkerThread(latch, "Worker-" + i);
            executorService.execute(worker);
        }

        System.out.println("Main thread is waiting for all workers to complete their tasks...");
        latch.await(); // 主线程在此等待,直到计数器变为0

        System.out.println("All workers have completed their tasks. Main thread is now continuing.");
        executorService.shutdown();
    }
}

class WorkerThread implements Runnable {
    private final CountDownLatch latch;
    private final String name;

    WorkerThread(CountDownLatch latch, String name) {
        this.latch = latch;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000); // 模拟执行任务
            System.out.println(name + " has finished the task.");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            latch.countDown(); // 完成任务后计数减一
        }
    }
}

在这个例子中,我们创建了一个固定大小的线程池来执行5个WorkerThread任务。每个工作线程完成自己的任务后会调用latch.countDown()减少计数器的值。主线程则通过调用latch.await()等待,直到所有的工作线程都完成了它们的任务(即计数器变为0),之后主线程才会继续执行。

  • 17
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值