标签: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(); } } }
标签:time main val fixed this 执行 service ack rgs
原文地址:https://www.cnblogs.com/moris5013/p/11846126.html