CountDownLatch闭锁

本文介绍了CountDownLatch同步辅助类的基本概念及应用场景,并通过示例代码详细解释了如何利用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值