有人可以帮我理解Java CountDownLatch是什么以及何时使用它?
我对这个程序的工作原理并不十分清楚.据我所知,所有三个线程立即启动,每个线程将在3000ms后调用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();
}
}
Run Code Online (Sandbox Code Playgroud)
// ------------------------------------------------ -----
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 …Run Code Online (Sandbox Code Playgroud)