CountDownLatch闭锁

CountDownLatch是一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。

闭锁可以延迟线程的进度直到其到达终止状态,闭锁可以用来确保某些活动直到其他活动都完成才继续执行:

  • 确保某个计算在其需要的所有资源都被初始化之后才继续执行;
  • 确保某个服务在其依赖的所有其他服务都已经启动之后才启动;
  • 等待直到某个操作所有参与者都准备就绪再继续执行。

下面可以通过一段代码来更好地理解CountDownLatch。

 1 package com.ccfdod.juc;
 2 
 3 import java.util.concurrent.CountDownLatch;
 4 
 5 /**
 6  * CountDownLatch:闭锁,在完成某些运算时,只有其他所有线程的运算全部完成,当前运算才继续执行
 7  */
 8 public class TestCountDownLatch {
 9 
10     public static void main(String[] args) {
11         final CountDownLatch latch = new CountDownLatch(5);
12         LatchDemo ld = new LatchDemo(latch);
13         
14         long start = System.currentTimeMillis();
15         //这里如果i<8(大于5的数,5对应new CountDownLatch(5)),那么在在至少5个线程完成后,执行打印耗费时间语句
16         for(int i=0; i<5; i++) {
17             new Thread(ld).start();
18         }
19         try {
20             latch.await();
21         } catch (InterruptedException e) {
22             
23         }
24         long end = System.currentTimeMillis();
25         System.out.println("好费时间为:" + (end - start));
26     }
27 }
28 
29 class LatchDemo implements Runnable {
30     private CountDownLatch latch;
31     
32     public LatchDemo(CountDownLatch latch) {
33         this.latch = latch;
34     }
35 
36     @Override
37     public void run() {
38         try {
39             for (int i = 0; i < 200; i++) {
40                 if (i % 2 == 0) {
41                     System.out.println(i);
42                 }
43             }
44         } finally {
45             //在finally中保证一定能够执行
46             latch.countDown();
47         }
48     }
49 }
原文地址:https://www.cnblogs.com/ccfdod/p/6395995.html