一、概述
Fork/Join框架是Java7提供的一个用于并行执行任务的框架, 是一个把大任务分割成若干个小任务,最终汇总每个小任务结果后得到大任务结果的框架。(http://www.infoq.com/cn/articles/fork-join-introduction)
二、使用举例
计算从1加到1亿的总和。当然这里只是用来说明Fork/Join框架的使用方法,从最后的运行结果中也可以看出就这个任务采用Fork/Join框架并没有提高性能,性能反而低于单个线程。原因是这个任务太简单了,采用Fork/Join框架的好处远远低于创建线程和线程调度切换的开销。
package com.my.test9;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
/**
* Title: <br/>
* Intention: <br/>
* <p>
* Class Name: com.my.test9.SumTest<br/>
* Create Date: 2017/9/3 16:56 <br/>
* Project Name: MyTest <br/>
* Company: All Rights Reserved. <br/>
* Copyright © 2017 <br/>
* </p>
* <p>
* author: GaoWei <br/>
* 1st_examiner: <br/>
* 2nd_examiner: <br/>
* </p>
*
* @version 1.0
* @since JDK 1.7
*/
public class SumTask extends RecursiveTask<Long>{
private Long start;
private Long end;
private static Long threshHold = 10000000L;
public SumTask(Long start, Long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
Long sum = 0L;
if (end - start <= threshHold) {
for (long i = start; i <= end; i++) {
sum += i;
}
} else {
long middle = (end + start)/2;
SumTask taskLeft = new SumTask(start, middle);
SumTask taskRight = new SumTask(middle + 1, end);
taskLeft.fork();
taskRight.fork();
Long leftResult = taskLeft.join();
Long rightResult = taskRight.join();
sum = leftResult + rightResult;
}
return sum;
}
public static void main(String[] args) throws Exception{
Long num = 100000000L;
long start = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool();
SumTask task = new SumTask(1L, num);
Future<Long> future = forkJoinPool.submit(task);
System.out.println("result = "+future.get());
long end = System.currentTimeMillis();
System.out.println("fork join 耗时="+(end - start));
start = System.currentTimeMillis();
long sum = 0L;
for(long i=1;i<=num;i++){
sum += i;
}
end = System.currentTimeMillis();
System.out.println("result = "+sum +", for 循环耗时="+(end - start));
}
}
运行结果:
result = 5000000050000000
fork join 耗时=577
result = 5000000050000000, for 循环耗时=43
参考:
1、http://www.infoq.com/cn/articles/fork-join-introduction