CountDownLatch是一个计数器,只不是事原子操作。不过这一点在多线程里面是很重要的
应用场景是:有一个任务想要往下执行,但必须要等到其他的任务执行完毕后才可以继续往下执行。
直接展示代码
public class CountDownLatch {
public static void main(String[] args) {
java.util.concurrent.CountDownLatch countDownLatch = new java.util.concurrent.CountDownLatch(3);
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 3; i++) {
executorService.submit(() -> {
System.out.println("start...");
try {
//do something
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
// finish process,you need call
countDownLatch.countDown();
});
}
try {
//wait all finish process
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("finished..");
}
}
我相信上门这段代码能够足够说明问题了