zoukankan      html  css  js  c++  java
  • CountdownLatch例子

    CountdownLatch 一个线程或者多个线程等待其他线程完成了再接着往下执行

    public class CountDownLatchTest {
    
        private static ExecutorService executorService = Executors.newFixedThreadPool(2);
        private static Random random = new Random(System.currentTimeMillis());
        private static CountDownLatch latch = new CountDownLatch(10);
    
        public static void main(String[] args) throws InterruptedException {
            //(1)
            int[] data = query();
            //(2)
            for (int i = 0; i < data.length; i++) {
                executorService.execute(new SimRunnable(data, i, latch));
            }
            //(3)
            latch.await();
            System.out.println("all of work  have finished");
            executorService.shutdown();
        }
    
        public static int[] query() {
            return new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        }
    
        static class SimRunnable implements Runnable {
            private int[] data;
            private int index;
            private CountDownLatch countDownLatch;
    
            SimRunnable(int[] data, int index, CountDownLatch countDownLatch) {
                this.data = data;
                this.index = index;
                this.countDownLatch = countDownLatch;
            }
    
            @Override
            public void run() {
                try {
                    Thread.sleep(random.nextInt(2000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int value = data[index];
                if (value % 2 == 0) {
                    data[index] = value + 30;
                } else {
                    data[index] = value * 2;
                }
                countDownLatch.countDown();
                System.out.println("work " + index + " has finished");
            }
        }
    
    
    }
  • 相关阅读:
    Docker GitLab镜像部署
    Kubernetes集群部署之三ETCD集群部署
    Kubernetes集群部署之二CA证书制作
    Kubernetes集群部署之一系统环境初始化
    docker开源仓库Harbor部署笔记
    git分支
    git高清技能图
    vue+uwsgi+nginx部署路飞学城
    git基础
    git安装与初始化
  • 原文地址:https://www.cnblogs.com/moris5013/p/11846126.html
Copyright © 2011-2022 走看看