码迷,mamicode.com
首页 > 其他好文 > 详细

countdownlatch例子

时间:2019-11-13 00:30:45      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:time   main   val   fixed   this   执行   service   ack   rgs   

countdownlatch 一个线程等待其他线程完成了再接着往下执行

public class CountDownLatchExample {

    private static ExecutorService executorService = Executors.newFixedThreadPool(2);
    private static Random random = new Random(System.currentTimeMillis());
    private static CountDownLatch countDownLatch = 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, countDownLatch));
        }
        //(3)
        countDownLatch.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;
            }
            System.out.println("work " + index + " has finished");
            countDownLatch.countDown();
        }
    }


}

 

 

countdownlatch例子

标签:time   main   val   fixed   this   执行   service   ack   rgs   

原文地址:https://www.cnblogs.com/moris5013/p/11846126.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!