CountDownLatch倒计时器

Posted mature1021

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CountDownLatch倒计时器相关的知识,希望对你有一定的参考价值。

package com.thread.dome;
 2 
 3 import java.util.concurrent.CountDownLatch;
 4 import java.util.concurrent.ExecutorService;
 5 import java.util.concurrent.Executors;
 6 
 7 public class CountDownLatchS {
 8     volatile static int i = 0;
 9     volatile static CountDownLatch countDownLatch = null;
10     volatile static CountDownLatch countDownLatch2 = null;
11 
12     public static void main(String[] args) throws Exception {
13         ExecutorService service = Executors.newFixedThreadPool(5);
14         countDownLatch = new CountDownLatch(5);// 五个
15         countDownLatch2 = new CountDownLatch(1);
16         for (; i < 5; i++) {
17 
18             Runnable runnable = new Runnable() {
19 
20                 @Override
21                 public void run() {
22 
23                     System.out.println("Matuew:" + Thread.currentThread().getName() + ":等待中");
24                     try {
25                         countDownLatch2.await();
26                     } catch (InterruptedException e1) {
27                         // TODO Auto-generated catch block
28                         e1.printStackTrace();
29                     }
30                     try {
31 
32                         Thread.sleep(1000);
33 
34                         countDownLatch.countDown();
35                         System.out.println("Matuew:" + Thread.currentThread().getName() + ":执行完成");
36                     } catch (InterruptedException e) {
37                         // TODO Auto-generated catch block
38                         e.printStackTrace();
39                     }
40 
41                 }
42             };
43             service.execute(runnable);
44 
45         }
46 
47         System.out.println(Thread.currentThread().getName() + ">等待五秒,再执行...");
48         Thread.sleep(5000);
49         countDownLatch2.countDown();
50         System.out.println("开始执行:");
51 
52     }
53 }
54 
55 
56 main>等待五秒,再执行...
57 Matuew:pool-1-thread-2:等待中
58 Matuew:pool-1-thread-3:等待中
59 Matuew:pool-1-thread-4:等待中
60 Matuew:pool-1-thread-5:等待中
61 Matuew:pool-1-thread-1:等待中
62 开始执行:
63 Matuew:pool-1-thread-2:执行完成
64 Matuew:pool-1-thread-3:执行完成
65 Matuew:pool-1-thread-1:执行完成
66 Matuew:pool-1-thread-5:执行完成
67 Matuew:pool-1-thread-4:执行完成

 

以上是关于CountDownLatch倒计时器的主要内容,如果未能解决你的问题,请参考以下文章

3.1.5 倒计时器:CountDownLatch

CountDownLatch倒计时器

并发工具类:倒计时器-CountDownLatch

多线程控制工具类--倒计时器CountDownLatch的使用(模仿火箭发射)

java并发学习03---CountDownLatch 和 CyclicBarrier

线程工具类 - CountDownLatch