zoukankan      html  css  js  c++  java
  • 16.Java5的CountDownLatch同步工具

     1 import java.util.concurrent.CountDownLatch;
     2 import java.util.concurrent.ExecutorService;
     3 import java.util.concurrent.Executors;
     4 
     5 /**
     6  * 16.Java5的CountDownLatch同步工具
     7  * 犹如倒计时计数器,调用CountDownLatch对象的CountDown方法就将计数器减1,
     8  * 当计数到达0事,则所有等待者或单个等待着开始执行。
     9  * 
    10  * @author LiTaiQing
    11  *
    12  */
    13 public class CountdownLatchTest {
    14 
    15     public static void main(String[] args) {
    16         ExecutorService service = Executors.newCachedThreadPool();
    17         final CountDownLatch cdOrder = new CountDownLatch(1);
    18         final CountDownLatch cdAnswer = new CountDownLatch(3);
    19         for (int i = 0; i < 3; i++) {
    20             Runnable runnable = new Runnable() {
    21                 public void run() {
    22                     try {
    23                         System.out.println("线程"
    24                                 + Thread.currentThread().getName() + "正准备接受命令");
    25                         cdOrder.await();
    26                         System.out.println("线程"
    27                                 + Thread.currentThread().getName() + "已接受命令");
    28                         Thread.sleep((long) (Math.random() * 10000));
    29                         System.out
    30                                 .println("线程"
    31                                         + Thread.currentThread().getName()
    32                                         + "回应命令处理结果");
    33                         cdAnswer.countDown();
    34                     } catch (Exception e) {
    35                         e.printStackTrace();
    36                     }
    37                 }
    38             };
    39             service.execute(runnable);
    40         }
    41         try {
    42             Thread.sleep((long) (Math.random() * 10000));
    43 
    44             System.out.println("线程" + Thread.currentThread().getName()
    45                     + "即将发布命令");
    46             cdOrder.countDown();
    47             System.out.println("线程" + Thread.currentThread().getName()
    48                     + "已发送命令,正在等待结果");
    49             cdAnswer.await();
    50             System.out.println("线程" + Thread.currentThread().getName()
    51                     + "已收到所有响应结果");
    52         } catch (Exception e) {
    53             e.printStackTrace();
    54         }
    55         service.shutdown();
    56 
    57     }
    58 }
  • 相关阅读:
    DataTable进行排序Asc升序,Desc降序
    Money型字段小数点后保留两位小数
    删除RHSA文件方法
    PowerDesigner 同名问题解决 Entity Attribute name uniqueness
    Repeater嵌套绑定Repeater以及内层调用外层数据
    让A超链接无效的办法 阻止元素发生默认的行为
    图的遍历
    Modular Production Line
    网络流24题-最长k可重区间集问题
    运输计划
  • 原文地址:https://www.cnblogs.com/litaiqing/p/4650998.html
Copyright © 2011-2022 走看看