标签:
import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveTask; /** * @author Vincent Zhao * @version 1.0.0 * @Time 2015/4/18 13:15 */ public class ForkJoinDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { ForkJoinPool pool = new ForkJoinPool(); ForkJoinTask<Long> submit = pool.submit(new Calculator(0, 1000000)); System.out.println(submit.get()); } } class Calculator extends RecursiveTask<Long> { public static final int THRESHOLD = 100; private long start; private long end; public Calculator(long start, long end) { this.start = start; this.end = end; } @Override protected Long compute() { long sum = 0; if ((end - start) < THRESHOLD) { for (long i = start; i < end; i++) { sum += i; } } else { long 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; } }
标签:
原文地址:http://my.oschina.net/u/1792430/blog/403316