Java RecursiveTask create
import java.util.ArrayList; import java.util.List; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask; public class Main { public static void main(String[] args) { int numbers[] = new int[100000]; for (int i = 0; i < numbers.length; i++) { numbers[i] = i;/*www . ja va 2s. c o m*/ } long sum = 0L; long startTime = System.currentTimeMillis(); for (int i = 0; i < numbers.length; i++) { sum += numbers[i] * numbers[i]; } System.out.println("Sum of squares: " + sum); long stopTime = System.currentTimeMillis(); System.out.println("Iterative solution time: " + (stopTime - startTime)); ForkJoinPool forkJoinPool = new ForkJoinPool(); startTime = System.currentTimeMillis(); long result = forkJoinPool.invoke(new SumOfSquaresTask(numbers, 0, numbers.length)); System.out.println("forkJoinPool: " + forkJoinPool.toString()); System.out.println("forkJoinPool: " + forkJoinPool.toString()); stopTime = System.currentTimeMillis(); System.out.println("Sum of squares: " + result); System.out.println("Fork/join solution time: " + (stopTime - startTime)); } } class SumOfSquaresTask extends RecursiveTask<Long> { private static int numbers[] = new int[100000]; private int threshold = 1000; private int from; private int to; public SumOfSquaresTask(int[] data, int from, int to) { numbers = data; this.from = from; this.to = to; } @Override protected Long compute() { long sum = 0L; int mid = (to + from) >>> 1; if ((to - from) < threshold) { for (int i = from; i < to; i++) { sum += numbers[i] * numbers[i]; } return sum; } else { List<RecursiveTask<Long>> forks = new ArrayList<>(); SumOfSquaresTask task1 = new SumOfSquaresTask(numbers, from, mid); SumOfSquaresTask task2 = new SumOfSquaresTask(numbers, mid, to); forks.add(task1); task1.fork(); forks.add(task2); task2.fork(); for (RecursiveTask<Long> task : forks) { sum += task.join(); } return sum; } } }