【发布时间】:2023-03-21 23:56:01
【问题描述】:
谁能帮我理解 Java CountDownLatch 是什么以及何时使用它?
我对这个程序的工作原理不是很清楚。据我了解,所有三个线程同时启动,每个线程将在 3000 毫秒后调用 CountDownLatch。所以倒计时会一一递减。锁存器变为零后,程序会打印“已完成”。也许我理解的方式是不正确的。
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.");
}
}
【问题讨论】:
-
我刚刚将您的问题示例代码用于 android 并行服务批处理,它就像一个魅力。非常感谢!
-
从 2012 年的 this video 获得这里,这与此处显示的示例非常相似。对于任何感兴趣的人,这是来自一个名叫 John 的人的 Java 多线程教程系列的一部分。我喜欢约翰。强烈推荐。
标签: java multithreading countdown countdownlatch