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 }
  • 相关阅读:
    《入门经典》——6.15
    《Linear Algebra and Its Application》-chaper1-行化简法解决线性方程组
    《算法实战策略》-chaper19-队列、栈和双端队列
    《Linear Algebra and Its Applications》-chaper1-向量方程、矩阵方程和线性方程组
    辛普森法则
    《训练指南》——6.15
    《入门经典》——6.21
    《算法问题实战策略》-chaper13-数值分析
    Scheme 中的 pair 和 list 简述
    C. Friends
  • 原文地址:https://www.cnblogs.com/litaiqing/p/4650998.html
Copyright © 2011-2022 走看看