zoukankan      html  css  js  c++  java
  • 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:执行完成
  • 相关阅读:
    Codeforces Round #567 (Div. 2) B. Split a Number
    es界面的分组,求平均值的操作
    es界面的查询命令
    es界面的crud
    WebStorm中自定义文档注释模板
    Vue 正确理解mounted、beforeUpdate、updated三个钩子函数的关系
    oracle分析函数
    vue中时间格式的处理
    vue-router params和query的区别
    vue中的深拷贝理解和实现
  • 原文地址:https://www.cnblogs.com/mature1021/p/9493165.html
Copyright © 2011-2022 走看看