首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Java多线程中使用CountDownLatch?

如何在Java多线程中使用CountDownLatch?
EN

Stack Overflow用户
提问于 2013-07-24 14:47:48
回答 7查看 131.1K关注 0票数 202

有没有人能帮我理解一下Java CountDownLatch是什么,什么时候用?

我不是很清楚这个程序是如何工作的。据我所知,所有三个线程同时启动,每个线程将在3000ms后调用CountDownLatch。所以倒计时将一个接一个地递减。当latch变为零后,程序会打印“已完成”。也许我理解的方式是不正确的。

代码语言:javascript
复制
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();
    }
}

//

代码语言:javascript
复制
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.");
    }

}
EN

回答 7

Stack Overflow用户

发布于 2014-03-19 14:54:16

Java语言中的CountDownLatch是一种同步器,它允许一个Thread在开始处理之前等待一个或多个Thread

CountDownLatch的工作原理是锁存,线程会一直等到门打开。一个线程等待创建CountDownLatch时指定的n线程数。

例如final CountDownLatch latch = new CountDownLatch(3);

这里我们将计数器设置为3。

任何调用CountDownLatch.await()的线程,通常是应用程序的主线程,都会一直等到计数为零,或者被另一个Thread中断。所有其他线程在完成或准备好执行作业后,都需要通过调用CountDownLatch.countDown()进行倒计时。一旦计数达到零,等待的Thread就开始运行。

在这里,计数是通过CountDownLatch.countDown()方法递减的。

调用await()方法的Thread将等待,直到初始计数为零。

要使计数为零,其他线程需要调用countDown()方法。一旦计数变为零,调用await()方法的线程将恢复(开始执行)。

CountDownLatch的缺点是它不可重用:一旦计数变为零,它就不再可用。

票数 44
EN

Stack Overflow用户

发布于 2014-01-07 01:28:53

NikolaB很好地解释了这一点,但是示例有助于理解,所以这里有一个简单的示例……

代码语言:javascript
复制
 import java.util.concurrent.*;


  public class CountDownLatchExample {

  public static class ProcessThread implements Runnable {

    CountDownLatch latch;
    long workDuration;
    String name;

    public ProcessThread(String name, CountDownLatch latch, long duration){
        this.name= name;
        this.latch = latch;
        this.workDuration = duration;
    }


    public void run() {
        try {
            System.out.println(name +" Processing Something for "+ workDuration/1000 + " Seconds");
            Thread.sleep(workDuration);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name+ "completed its works");
        //when task finished.. count down the latch count...

        // basically this is same as calling lock object notify(), and object here is latch
        latch.countDown();
    }
}


public static void main(String[] args) {
    // Parent thread creating a latch object
    CountDownLatch latch = new CountDownLatch(3);

    new Thread(new ProcessThread("Worker1",latch, 2000)).start(); // time in millis.. 2 secs
    new Thread(new ProcessThread("Worker2",latch, 6000)).start();//6 secs
    new Thread(new ProcessThread("Worker3",latch, 4000)).start();//4 secs


    System.out.println("waiting for Children processes to complete....");
    try {
        //current thread will get notified if all chidren's are done 
        // and thread will resume from wait() mode.
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("All Process Completed....");

    System.out.println("Parent Thread Resuming work....");



     }
  }
票数 24
EN

Stack Overflow用户

发布于 2014-06-05 11:33:14

CoundDownLatch使您能够让线程等待,直到所有其他线程执行完毕。

伪代码可以是:

代码语言:javascript
复制
// Main thread starts
// Create CountDownLatch for N threads
// Create and start N threads
// Main thread waits on latch
// N threads completes there tasks are returns
// Main thread resume execution
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17827022

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档