fork/Join框架的思想是将一个规模为n的大任务,fork成几个规模较小的K个子任务,最后合并所有子任务的结果,返回最终结果。
如图一个规模为T的任务划分成12个子任务,分别有4个线程在执行。如果当前线程没有可执行任务时,会从其他线程的任务队列中窃取任务来执行。工作窃取算法保证了cpu不会处于空闲状态。
public class MySumTask extends RecursiveTask {
private int[] data;
private int begin;
private int end;
@Override
protected Integer compute() {
//最小划分粒度
if (end-begin<=2){
int result=0;
for (int i = begin; i
打印统计结果
public static void main(String[] args) {
int[] dataArr=new int[]{1,2,3,4,6,7,8};
MySumTask mySumTask=new MySumTask(dataArr,0,dataArr.length);
ForkJoinPool pool=new ForkJoinPool();
System.out.println("sum result="+pool.invoke(mySumTask));
}
public class MyPrintTask extends RecursiveAction {
private int[] data;
private int begin;
private int end;
@Override
protected void compute() {
//最小划分粒度
if (end-begin<=2){
StringBuilder builder=new StringBuilder("[");
for (int i = begin; i
等待所有任务执行结束
public static void main(String[] args) throws Exception{
int[] dataArr=new int[]{1,2,3,4,6,7,8};
MyPrintTask mySumTask=new MyPrintTask(dataArr,0,dataArr.length);
ForkJoinPool pool=new ForkJoinPool();
//提交任务
pool.submit(mySumTask);
//等待所有任务完成
pool.awaitTermination(2, TimeUnit.SECONDS);
}
如下所示代码,利用Java8的并行流,对1到5的数进行相乘
public static void main(String[] args) {
Stream.of(1,2,3,4,5).parallel().reduce((x, y)->x*y).ifPresent(System.out::println);
}
设置了sourceStage.parallel 值为true
abstract class AbstractPipeline{
@Override
@SuppressWarnings("unchecked")
public final S parallel() {
sourceStage.parallel = true;
return (S) this;
}
}
evaluate方法,会调用isParallel(),对上面的sourceStage.parallel进行判断
abstract class ReferencePipeline{
@Override
public final Optional reduce(BinaryOperator accumulator) {
return evaluate(ReduceOps.makeRef(accumulator));
}
final R evaluate(TerminalOp terminalOp) {
// 判断sourceStage.parallel是否为true
return isParallel()
? terminalOp.evaluateParallel(this, sourceSpliterator(terminalOp.getOpFlags()))
: terminalOp.evaluateSequential(this, sourceSpliterator(terminalOp.getOpFlags()));
}
}
接口TerminalOp
interface TerminalOp {
default R evaluateParallel(PipelineHelper helper,
Spliterator spliterator) {
if (Tripwire.ENABLED)
Tripwire.trip(getClass(), "{0} triggering TerminalOp.evaluateParallel serial default");
return evaluateSequential(helper, spliterator);
}
}
实现类ReduceOps新建了ReduceTask对象
final class ReduceOps {
@Override
public R evaluateParallel(PipelineHelper helper,
Spliterator spliterator) {
return new ReduceTask<>(this, helper, spliterator).invoke().get();
}
}
由此我们可以看出,Java8的Stream并行流底层代码,确实采用了Fork/Join框架来实现