SumParallel.java


Below is the syntax highlighted version of SumParallel.java.


import java.util.concurrent.*;
public class SumParallel {

   static int total;

   public static void main(String[] args) {
      total = 0;

      int n = Integer.parseInt(args[0]);

      // keep track of all the things we execute
      ExecutorService pool = Executors.newCachedThreadPool();

      for (int i=1; i<=n; i++) {
         int increment = i; // effectively final
         Runnable r =
            ()
            ->
            {
               synchronized (SumParallel.class) { // lock-ish
                  total += increment;
            }
         };
         pool.execute(r);
      }

      pool.shutdown();
      while (!pool.isTerminated()) Thread.yield();

      System.out.println(total);
   }
}