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");
        }
    }


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