有人可以帮助我了解Java CountDownLatch
是什么以及何时使用它?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.");
}
}
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html –
我刚刚使用您的问题示例代码进行android并行服务批处理,它的工作方式就像一个魅力。非常感谢! – Roisgoen