0
private static void calculateSum1() throws InterruptedException, ExecutionException {
        CountDownLatch latch = new CountDownLatch(3);
        int[] a = {1, 2, 3, 4, 5, 7};
        int[] b = {8, 9, 10, 11, 12, 13};
        int[] c = {14, 15, 16, 17, 18, 19, 20};

        ExecutorService service = Executors.newFixedThreadPool(3);
        Future<Integer> resultA = service.submit(new Worker(a, latch));
        Future<Integer> resultB = service.submit(new Worker(b, latch));
        Future<Integer> resultC = service.submit(new Worker(c, latch));


        latch.await();

        Integer ra = resultA.get();
        Integer rb = resultB.get();
        Integer rc = resultC.get();


        System.out.println("the result is :" + (ra + rb + rc));
    }
class Worker implements Callable<Integer> {
    int[] arr;
    CountDownLatch latch;

    public Worker(int[] arr, CountDownLatch latch) {
        arr = arr;
        latch = latch;
    }


    @Override
    public Integer call() throws Exception {
        System.out.println("about to calculate sum of :" + arr.toString());
        try {
            int sum = IntStream.of(arr).sum();
            System.out.println(Thread.currentThread().getName() + ":" +sum);
            return sum;
        }finally {
            latch.countDown();
        }
    }
}

The thread dump shows:

"main" #1 prio=5 os_prio=0 tid=0x0000000002f82800 nid=0x4e4 waiting on condition [0x0000000002d7f000] java.lang.Thread.State: WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for <0x00000000d5ffb840> (a java.util.concurrent.CountDownLatch$Sync) at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175) at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:836) at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(AbstractQueuedSynchronizer.java:997) at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1304) at java.util.concurrent.CountDownLatch.await(CountDownLatch.java:231)

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Aaron
  • 43
  • 7
  • 2
    `arr = arr; latch = latch;` does nothing. – tkausl Jun 11 '20 at 13:53
  • Um, what @tkausl is trying to tell you is that the formal parameters, `arr` and `latch`, in your `Worker` constructor _[shadow](https://en.wikipedia.org/wiki/Variable_shadowing)_ the member variables with the same names. The member variables are inaccessible to the constructor because of the shadowing. One solution is to re-name the formal params, (e.g., `arr_` instead of `arr`, and then write `arr = arr_;` – Solomon Slow Jun 11 '20 at 17:01
  • once the shadowing issue is addressed this seems to work fine. use Arrays.toString to display your arrays, and use shutdownNow on your executor when you're done with it so that this exits cleanly. voting to close this as a typo. – Nathan Hughes Jun 11 '20 at 17:41

0 Answers0