zoukankan      html  css  js  c++  java
  • 10.线程通信CountDownLatch

    CountDownLatch
    1.一个同步的辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个、多个线程去一直等待,用给定的计数、初始化“CountDownLatch”。
      由于调用 countDown()方法 ,所以在当前计算到达之前,await()方法会一直处于阻塞状态,之后会释放所有的等待线程,await()方法的所有
      后续调用都将立即返回调用。
    1. public class CountDownLatchTest {
    2. // 模拟了100米赛跑,10名选手已经准备就绪,只等裁判一声令下。当所有人都到达终点时,比赛结束。
    3. public static void main(String[] args) throws InterruptedException {
    4. // 开始的倒数锁
    5. final CountDownLatch begin = new CountDownLatch(1);
    6. // 结束的倒数锁
    7. final CountDownLatch end = new CountDownLatch(10);
    8. // 十名选手
    9. final ExecutorService exec = Executors.newFixedThreadPool(10);
    10. for (int index = 0; index < 10; index++) {
    11. final int NO = index + 1;
    12. Runnable run = new Runnable() {
    13. public void run() {
    14. try {
    15. // 如果当前计数为零,则此方法立即返回。
    16. // 等待
    17. begin.await();
    18. Thread.sleep((long) (Math.random() * 10000));
    19. System.out.println("No." + NO + " arrived");
    20. } catch (InterruptedException e) {
    21. } finally {
    22. // 每个选手到达终点时,end就减一
    23. end.countDown();
    24. }
    25. }
    26. };
    27. exec.submit(run);
    28. }
    29. System.out.println("Game Start");
    30. // begin减一,开始游戏
    31. begin.countDown();
    32. // 等待end变为0,即所有选手到达终点
    33. end.await();
    34. System.out.println("Game Over");
    35. exec.shutdown();
    36. }
    37. }
    38. Game Start
      No.9 arrived
      No.6 arrived
      No.8 arrived
      No.7 arrived
      No.10 arrived
      No.1 arrived
      No.5 arrived
      No.4 arrived
      No.2 arrived
      No.3 arrived
      Game Over


    2.需要等待某个条件到达之后才能做后续下一步的业务,同时当前线程完成后也会触发事件,以便进行后面的操作。



  • 相关阅读:
    Leetcode Binary Tree Preorder Traversal
    Leetcode Minimum Depth of Binary Tree
    Leetcode 148. Sort List
    Leetcode 61. Rotate List
    Leetcode 86. Partition List
    Leetcode 21. Merge Two Sorted Lists
    Leetcode 143. Reorder List
    J2EE项目应用开发过程中的易错点
    JNDI初认识
    奔腾的代码
  • 原文地址:https://www.cnblogs.com/xxt19970908/p/7302403.html
Copyright © 2011-2022 走看看