zoukankan      html  css  js  c++  java
  • Java中CountDownLatch使用初步

    package gj.lang.util.concurrent.countdonwlatch;
    
    import java.util.Random;
    import java.util.concurrent.CountDownLatch;
    
    /**
     * Author: areful
     * Date: 2019/4/24
     */
    public class CountDownLatchSample {
        private static class Player implements Runnable {
            private int id;
            private CountDownLatch beginCountDownLatch;
            private CountDownLatch endCountDownLatch;
    
            private Player(int id, CountDownLatch begin, CountDownLatch end) {
                this.id = id;
                this.beginCountDownLatch = begin;
                this.endCountDownLatch = end;
            }
    
            @Override
            public void run() {
                try {
                    beginCountDownLatch.await();
                    System.out.println("CyclicBarrierSample " + id + "起跑...");
    
                    Thread.sleep(new Random().nextInt(1000));
                    System.out.println("CyclicBarrierSample " + id + " 到达终点");
    
                    endCountDownLatch.countDown();
                    System.out.println("CyclicBarrierSample " + id + "继续干其他事情");
                } catch (InterruptedException ignored) {
                }
            }
        }
    
        public static void main(String[] args) {
            final int PLAYER_NUM = 5;
            CountDownLatch beginCountDownLatch = new CountDownLatch(1);
            CountDownLatch endCountDownLatch = new CountDownLatch(PLAYER_NUM);
    
            for (int i = 0; i < PLAYER_NUM; i++) {
                new Thread(new Player(i, beginCountDownLatch, endCountDownLatch)).start();
            }
    
            try {
                System.out.println("统一起跑");
                beginCountDownLatch.countDown();
    
                endCountDownLatch.await(); //等待所有运动员到达终点
                System.out.println("结果发送到汇报成绩的系统");
            } catch (InterruptedException ignored) {
            }
        }
    }
    

       

    输出结果:

  • 相关阅读:
    省市三级联动
    Python 函数中,参数是传值,还是传引用?
    CSRF(Cross Site Request Forgery, 跨站域请求伪造)
    Django 中间件
    python的内存管理机制
    adb的一些常用的命令
    ant使用备忘
    关于如何以编程的方式执行TestNG
    关于使用testng的retry问题
    SSH中将hibernate托管给spring获取session的方法
  • 原文地址:https://www.cnblogs.com/areful/p/10763562.html
Copyright © 2011-2022 走看看