package com.wkx.test.forkJoin.containValue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
public class CountTask extends RecursiveTask<Integer>{
public static final int threshold = 2;
private int start;
private int end;
public CountTask(int start, int end)
{
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
int sum=0;
boolean canCompute=(end-start)<=threshold;
if(canCompute){
for(int i=start;i<=end;i++){
sum=sum+i;
}
}else{
int middle=(end-start)/2;
CountTask countTask1=new CountTask(start,middle);
CountTask countTask2=new CountTask(middle+1,end);
countTask1.fork();
countTask2.fork();
sum=countTask1.join()+countTask2.join();
}
return sum;
}
public static void main(String args[]) throws ExecutionException, InterruptedException {
ForkJoinPool joinPool=new ForkJoinPool();
CountTask countTask=new CountTask(0,3);
Future<Integer> result=joinPool.submit(countTask);
System.out.println(result.get());
}
}
ForkJoin 框架
点赞
收藏