import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask; public class ParallelSum extends RecursiveTask<Integer> { private int[] array; private int start; private int end; public ParallelSum(int[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override protected Integer compute() { if (end - start <= THRESHOLD) { int sum = 0; for (int i = start; i < end; i++) { sum += array[i]; } return sum; } else { int mid = (start + end) / 2; ParallelSum leftTask = new ParallelSum(array, start, mid); ParallelSum rightTask = new ParallelSum(array, mid, end); return leftResult + rightResult; } } public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; ForkJoinPool forkJoinPool = ForkJoinPool.commonPool(); ParallelSum task = new ParallelSum(array, 0, array.length); System.out.println("Sum: " + result); } }


上一篇:
下一篇:
切换中文