13. ForkJoinPool 分支/合并框架 工作窃取
Fork/Join 框架:就是在必要的情况下,将一个大任务,进行拆分(fork)成若干个小任务(拆到不可再拆时),再将一个个的小任务运算的结果进行 join 汇总
Fork/Join 框架class ForkJoinSumCalculate extends RecursiveTask<Long> {
private static final long serialVersionUID = -259195479995561737L;
private long start;
private long end;
/**
* 临界值
*/
private static final long THRESHOLD = 10000L;
public ForkJoinSumCalculate(long start, long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
long len = end - start;
if (len <= THRESHOLD) {
long sum = 0;
for (long i = start; i <= end; i++) {
sum += i;
}
return sum;
} else {
long middle = (start + end) / 2;
ForkJoinSumCalculate left = new ForkJoinSumCalculate(start, middle);
//进行拆分, 同时压入线程队列
left.fork();
ForkJoinSumCalculate right = new ForkJoinSumCalculate(middle, end);
//进行拆分, 同时压入线程队列
right.fork();
return left.join() + right.join();
}
}
}
测试
public static void main(String[] args) {
Instant start = Instant.now();
ForkJoinPool pool = new ForkJoinPool();
ForkJoinSumCalculate task = new ForkJoinSumCalculate(0L, 50000000000L);
Long sum = pool.invoke(task);
System.out.println(sum);
Instant end = Instant.now();
System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());
}
网友评论