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

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

问题描述

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

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

我不清楚这个程序是如何工作的。据我所知,所有三个线程一次启动,每个线程将在3000ms后调用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 在latch原理中工作,主线程将一直等到门打开。一个线程等待 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.

PS
OP的问题有一个非常简单的例子,所以我没有包含一个。

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

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

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