Java 多线程中如何使用 CountDownLatch? [英] How is CountDownLatch used in Java Multithreading?

查看:31
本文介绍了Java 多线程中如何使用 CountDownLatch?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我了解 Java CountDownLatch 是什么以及何时使用它吗?

Can someone help me to understand what Java CountDownLatch is and when to use it?

我对这个程序的工作原理不是很清楚.据我了解,所有三个线程同时启动,每个线程将在 3000 毫秒后调用 CountDownLatch.所以倒计时会一一递减.闩锁为零后,程序会打印已完成".可能我理解的方式不对.

I don't have a very clear idea of how this program works. As I understand all three threads start at once and each Thread will call CountDownLatch after 3000ms. So count down will decrement one by one. After latch becomes zero the program prints "Completed". Maybe the way I understood is incorrect.

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

class Processor implements Runnable {
    private CountDownLatch latch;

    public Processor(CountDownLatch latch) {
        this.latch = latch;
    }

    public void run() {
        System.out.println("Started.");

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        latch.countDown();
    }
}

//-------------------------------------------------

// -----------------------------------------------------

public class App {

    public static void main(String[] args) {

        CountDownLatch latch = new CountDownLatch(3); // coundown from 3 to 0

        ExecutorService executor = Executors.newFixedThreadPool(3); // 3 Threads in pool

        for(int i=0; i < 3; i++) {
            executor.submit(new Processor(latch)); // ref to latch. each time call new Processes latch will count down by 1
        }

        try {
            latch.await();  // wait until latch counted down to 0
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Completed.");
    }

}

推荐答案

是的,你理解正确.CountDownLatch 的工作原理是闩锁,主线程会一直等到门打开.一个线程等待 n 个线程,在创建 CountDownLatch 时指定.

Yes, you understood correctly. CountDownLatch works in latch principle, the main thread will wait until the gate is open. One thread waits for n threads, specified while creating the CountDownLatch.

任何线程,通常是应用程序的主线程,调用CountDownLatch.await() 将等待直到计数达到零或被另一个线程中断.一旦完成或准备好,所有其他线程都需要通过调用 CountDownLatch.countDown() 进行倒计时.

Any thread, usually the main thread of the application, which calls CountDownLatch.await() will wait until count reaches zero or it's interrupted by another thread. All other threads are required to count down by calling CountDownLatch.countDown() once they are completed or ready.

只要计数达到零,等待的线程就会继续.CountDownLatch 的缺点/优点之一是它不可重复使用:一旦计数达到零,您就不能再使用 CountDownLatch.

As soon as count reaches zero, the waiting thread continues. One of the disadvantages/advantages of CountDownLatch is that it's not reusable: once count reaches zero you cannot use CountDownLatch any more.

当一个线程(如主线程)需要等待一个或多个线程完成才能继续处理时,使用CountDownLatch.

Use CountDownLatch when one thread (like the main thread) requires to wait for one or more threads to complete, before it can continue processing.

在 Java 中使用 CountDownLatch 的一个经典例子是服务器端核心 Java 应用程序,它使用服务架构,其中多个服务由多个线程提供,应用程序在所有服务启动成功后才能开始处理.

A classical example of using CountDownLatch in Java is a server side core Java application which uses services architecture, where multiple services are provided by multiple threads and the application cannot start processing until all services have started successfully.

附言OP 的问题有一个非常简单的例子,所以我没有包括一个.

P.S. OP's question has a pretty straightforward example so I didn't include one.

这篇关于Java 多线程中如何使用 CountDownLatch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆