4.闭锁 CountDownLatch

/*CountDownLatch 闭锁*/

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

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

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

 1 /*
 2  * CountDownLatch :闭锁,在完成某些运算时,只有其他线程的运算全部完成,当前运算才继续执行
 3  * 
 4  * CountDownLatch类是一个同步倒数计数器,构造时传入int参数,该参数就是计数器的初始值,每调用一次countDown()方法,计数器减1,
 5  * 
 6  * 计数器大于0 时,await()方法会阻塞后面程序执行,直到计数器为0,await(long timeout, TimeUnit unit),是等待一定时间,然后执行,不管计数器是否到0了。
 7  * */
 8 public class TestCountDownLatch {
 9     public static void main(String[] args) {
10         //创建闭锁
11         CountDownLatch latch = new CountDownLatch(5);
12         
13         LatchThread lt = new LatchThread(latch);
14 
15         long startTime = System.currentTimeMillis();
16 
17         for (int i = 0; i < 5; i++) {
18             new Thread(lt).start();
19         }
20         //让主线程进行等待,如果不使用闭锁,是无法得到 耗费的时间的,
21         //因为子线程 和 主线程是 并发的,所以需要让主线程等到 所有的子线程都执行完了,再去计算时间,才能得到结果
22         try {
23             latch.await();    //  > 0?
24         } catch (InterruptedException e) {
25 
26         }
27         long endTime = System.currentTimeMillis();
28         System.out.println("耗费:" + (endTime - startTime) + "毫秒");
29 
30     }
31 
32 }
33 
34 class LatchThread implements Runnable {
35     private CountDownLatch latch;
36 
37     public LatchThread(CountDownLatch latch) {
38         this.latch = latch;
39     }
40 
41     @Override
42     public void run() {
43         synchronized (this) {
44             try {
45                 for (int i = 0; i < 50000; i++) {
46                     if (i % 3 == 0) {
47                         System.out.println(i);
48                     }
49                 }
50             } finally {
51                 latch.countDown();       //-1
52             }
53         }
54     }
55 
56 }
原文地址:https://www.cnblogs.com/xuzekun/p/7428653.html