CountDownLatch闭锁

CountDownLatch闭锁

一、前言

  Java 5.0 在java.util.concurrent 包中提供了多种并发容器类来改进同步容器的性能。

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

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

  确保某个计算在其需要的所有资源都被初始化之后才继续执行;

  确保某个服务在其依赖的所有其他服务都已经启动之后才启动;

  等待直到某个操作所有参与者都准备就绪再继续执行。

二、代码示例

 1 package me.concurrrent.cdl;
 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     /**
12      * CountDownLatch翻译为中文就是倒计时阀门,每一个线程执行完成,构造器中的数字递减1
13      */
14     final CountDownLatch latch = new CountDownLatch(50);
15     LatchDemo ld = new LatchDemo(latch);
16 
17     long start = System.currentTimeMillis();
18 
19     for (int i = 0; i < 50; i++) {
20         new Thread(ld).start();
21     }
22 
23     try {
24         /**
25          * 在latch.countDown();没有减为零之前主线程要等待
26          */
27         latch.await();
28     } catch (InterruptedException e) {
29     }
30 
31     long end = System.currentTimeMillis();
32 
33     System.out.println("耗费时间为:" + (end - start));
34     }
35 
36 }
37 
38 class LatchDemo implements Runnable {
39 
40     private CountDownLatch latch;
41 
42     public LatchDemo(CountDownLatch latch) {
43     this.latch = latch;
44     }
45 
46     @Override
47     public void run() {
48     //synchronized代码块保证线程安全问题
49     synchronized (this) {
50         try {
51         for (int i = 0; i < 50000; i++) {
52             if (i % 2 == 0) {
53             System.out.println(i);
54             }
55         }
56         } finally {
57         /**
58          * try-finally语句块保证这段代码一定执行 
59          * 每执行一次,CountDownLatch构造器中的数字减一
60          */
61         latch.countDown();
62         }
63     }
64 
65     }
66 
67 }
View Code

  要说的都在代码注释中了,有什么疑惑,欢迎评论区留言

  哈哈,这大概是我发的最短的一篇博文了

原文地址:https://www.cnblogs.com/albertrui/p/8401187.html