1,示例
import java.util.concurrent.RecursiveTask; public class Calculator extends RecursiveTask<Integer> { private static final int THRESHOLD = 4; private int start; private int end; public Calculator(int start, int end) { this.start = start; this.end = end; } @Override protected Integer compute() { int sum = 0; if((end-start) < THRESHOLD){ for(int i = start; i<= end;i++){ sum += i; } System.err.println(">>>>>>>>"); }else{ int middle = (start + end) /2; Calculator left = new Calculator(start, middle); Calculator right = new Calculator(middle + 1, end); left.fork(); right.fork(); sum = left.join() + right.join(); } return sum; } }
2 运行
import java.util.concurrent.ForkJoinPool; import java.util.concurrent.Future; public class Test { /** * @param args * @throws Exception * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException, Exception { // TODO Auto-generated method stub ForkJoinPool forkJoinPool = new ForkJoinPool(); Future<Integer> result = forkJoinPool.submit(new Calculator(0, 9)); //new Integer(49995000) System.err.println(result.get());
时间: 2024-10-10 04:42:32