Java中的CountDownLatch详解

Java中的CountDownLatch详解

大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!

一、什么是CountDownLatch?

CountDownLatch 是Java并发包中的一个工具类,用于实现线程间的等待。它允许一个或多个线程等待其他线程完成操作,然后再继续执行。CountDownLatch 的主要方法是 await()countDown(),分别用于线程等待和计数减少。

二、CountDownLatch的基本用法

在示例中,我们将展示如何使用 CountDownLatch 来实现一个主线程等待多个工作线程执行完毕后再继续执行的场景。

package cn.juwatech.concurrent;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3); // 初始化计数器为3

        Worker worker1 = new Worker(latch, "Worker-1");
        Worker worker2 = new Worker(latch, "Worker-2");
        Worker worker3 = new Worker(latch, "Worker-3");

        worker1.start();
        worker2.start();
        worker3.start();

        latch.await(); // 主线程等待所有工作线程完成

        System.out.println("All workers have finished their work.");
    }

    static class Worker extends Thread {
        private CountDownLatch latch;

        public Worker(CountDownLatch latch, String name) {
            super(name);
            this.latch = latch;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " is working.");
            try {
                Thread.sleep(1000); // 模拟工作耗时
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " has finished.");
            latch.countDown(); // 每个工作线程完成后计数器减一
        }
    }
}

三、代码解析

  1. main 方法中,创建了一个 CountDownLatch 实例 latch,初始计数为3。
  2. 创建了三个工作线程 Worker,每个线程在执行完模拟工作后,调用 latch.countDown() 来减少计数器。
  3. 主线程调用 latch.await() 来等待计数器归零,即所有工作线程执行完毕。
  4. 执行结果将输出所有工作线程完成后的提示信息。

四、总结

通过本文的示例,我们学习了如何利用 CountDownLatch 实现线程间的协作。它常用于多个线程之间的同步,主要用途包括等待多个子线程完成某项任务后再执行接下来的操作。

著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!

posted @ 2024-07-13 15:27  省赚客开发者团队  阅读(1)  评论(0编辑  收藏  举报