版权声明:本文为博主原创文章,转载请说明出处 https://blog.csdn.net/u010002184/article/details/83343132
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(5);
Service service = new Service(latch);
Runnable task = () -> service.exec();
for (int i = 0; i < 5; i++) {
Thread thread = new Thread(task);
thread.start();
}
System.out.println("main thread await. ");
latch.await();
System.out.println("main thread finishes await. ");
}
}
class Service {
private CountDownLatch latch;
public Service(CountDownLatch latch) {
this.latch = latch;
}
public void exec() {
try {
System.out.println(Thread.currentThread().getName() + " execute task. ");
sleep(2);
System.out.println(Thread.currentThread().getName() + " finished task. ");
//System.out.println(1/0);//即使发生异常,也会执行finally{}中的代码,但finally{}之后的代码不会执行
} finally {
latch.countDown();
System.out.println(latch.getCount());
}
//System.out.println(111111111);//try中发生异常时此行代码不会执行,正常时才会执行
}
private void sleep(int seconds) {
try {
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出:
Thread-0 execute task.
main thread await.
Thread-1 execute task.
Thread-3 execute task.
Thread-2 execute task.
Thread-4 execute task.
Thread-0 finished task.
4
Thread-1 finished task.
3
Thread-3 finished task.
2
Thread-4 finished task.
Thread-2 finished task.
1
0
main thread finishes await.
CountDownLatch中count down是倒数的意思,latch则是门闩的含义。整体含义可以理解为倒数的门栓,似乎有一点“三二一,芝麻开门”的感觉。CountDownLatch的作用也是如此,在构造CountDownLatch的时候需要传入一个整数n,在这个整数“倒数”到0之前,主线程需要等待在门口,而这个“倒数”过程则是由各个执行线程驱动的,每个线程执行完一个任务“倒数”一次。总结来说,CountDownLatch的作用就是等待其他的线程都执行完任务,必要时可以对各个任务的执行结果进行汇总,然后主线程才继续往下执行。
参考:https://www.jianshu.com/p/128476015902