1 private class SumTask extends RecursiveTask<Long> { 2 3 private static final int THRESHOLD = 1250000; 4 5 private long arr[]; 6 private int start; 7 private int end; 8 9 public SumTask(long[] arr, int start, int end) { 10 this.arr = arr; 11 this.start = start; 12 this.end = end; 13 } 14 15 /** 16 * 小计 17 */ 18 private long subtotal() { 19 long sum = 0; 20 for (int i = start; i < end; i++) { 21 sum += arr[i]; 22 } 23 24 return sum; 25 } 26 27 @Override 28 protected Long compute() { 29 30 if ((end - start) <= THRESHOLD) { 31 return subtotal(); 32 }else { 33 int middle = (start + end) / 2; 34 SumTask left = new SumTask(arr, start, middle); 35 SumTask right = new SumTask(arr, middle, end); 36 left.fork(); 37 right.fork(); 38 39 return left.join() + right.join(); 40 } 41 } 42 } 43 44 public static void main(String[] args) throws ExecutionException, InterruptedException{ 45 int num = Runtime.getRuntime().availableProcessors(); 46 long time = System.currentTimeMillis(); 47 long[] arr = new long[10000000]; 48 for (int i =0 ; i < 10000000; i++) { 49 arr[i] =i+1; 50 } 51 52 ForkJoinPool pool = new ForkJoinPool(); 53 ForkJoinTask<Long> result = pool.submit(new ForkJoinTest().new SumTask(arr, 0, arr.length)); 54 System.out.println("最终计算结果: " + result.invoke()+"耗时:"+(System.currentTimeMillis() - time)+",毫秒"); 55 pool.shutdown(); 56 }