本例是把一个大的数组求和的计算的大任务分解到在小范围内求和的小任务,然后把这些小任务之和加起来就是所求之结果。
技术:JDK8.0, Javafork-join模式下的RecursiveTask技术,override compute().
- /**
- * Author: Bigtree
- * 本例是把一个大的数组求和的计算的大任务分解到在小范围内求和的小任务,然后把这些小任务之和加起来就是所求之结果。
- * 技术:
- * java fork-join模式下的RecursiveTask技术,override compute().
- */
- import java.util.*;
- import java.util.concurrent.*;
- class Caltask extends RecursiveTask<Long>{
- private static final int THRESHOLD = 1000; //how many numbers one thread can calculate
- private long data[];
- private int start;
- private int end;
- public Caltask(long[] inputData,int start, int end){
- data=inputData;
- this.start=start;
- this.end=end;
- }
- @Override
- protected Long compute() {
- Long sumResult=0L;
- if((end - start) <= THRESHOLD ){
- for(int index=start; index<end;index++) {
- sumResult += data[index];
- }
- }
- else { //parallel computing
- int step=(end-start)/THRESHOLD;
- if(((end-start)%THRESHOLD)>0)
- step+=1;
- ArrayList<Caltask> tasks = new ArrayList<>();
- int pos=start;
- int lastposition;
- for(int i=0;i<step;i++){
- lastposition=pos+THRESHOLD;
- if(lastposition>end)
- lastposition=end;
- Caltask onetask= new Caltask(data,pos,lastposition);
- pos=lastposition;
- tasks.add(onetask);
- onetask.fork();
- }
- for(Caltask mtask : tasks){
- sumResult += mtask.join();
- }
- }
- return sumResult;
- }
- }
- public class forkjoincompute {
- public static void ForkJoinShow(){
- long data[] = new long[20001];
- for(long i=0;i<data.length;i++){
- data[(int) i]= i + 1;
- }
- ForkJoinPool mypool= ForkJoinPool.commonPool();
- Future<Long> myfuture = mypool.submit( new Caltask(data,0,data.length));
- try{
- long result=myfuture.get();
- System.out.println("forkjoincompute():computed final result="+result);
- } catch(InterruptedException e){
- e.printStackTrace();
- } catch (ExecutionException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- mypool.shutdown();
- }
- }
输出结果:
forkjoincompute():computed final result=200030001