package com.ecloude.dycmsapi;
import java.util.ArrayList;
import java.util.List;
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> {
private static final int THRESHOLD = 4;// 阈值
private List<Integer> list;
public CountTask(List<Integer> list) {
// this.start = start;
// this.end = end;
this.list = list;
}
@Override
protected Integer compute() {
int sum = 0;
// 如果任务足够小就计算任务
boolean canCompute = list.size() <= THRESHOLD;
if (canCompute) {
return job(list);
} else {
// 如果任务大于阀值,就分裂成两个子任务计算
int middle = list.size() / 2;
CountTask leftTask = new CountTask(list.subList(0, middle));
CountTask rightTask = new CountTask(list.subList(middle,list.size()));
//执行子任务
// leftTask.fork();
// rightTask.fork();
// //等待子任务执行完,并得到其结果
// int leftResult=leftTask.join();
// int rightResult=rightTask.join();
//合并子任务
// sum = leftResult + rightResult;
invokeAll(leftTask, rightTask);
sum=getResults(leftTask.join(),rightTask.join());
}
return sum;
}
//合并抽题结果
public Integer getResults(Integer a, Integer b) {
System.out.println(Thread.currentThread().getName()+"开始合并结果......");
// 合并返回结果
System.out.println(Thread.currentThread().getName()+"合并结果结束......");
return a+b;
}
public Integer job(List<Integer> list){
System.out.println(Thread.currentThread().getName()+"do job start");
int sum =0;
for(Integer n:list){
System.out.println(Thread.currentThread().getName()+"do job "+n);
sum+=n;
}
System.out.println(Thread.currentThread().getName()+"do job end="+sum);
return list.size();
}
public static void main(String[] args) {
List<Integer> list=new ArrayList<Integer>();
for(int i=0;i<6;i++){
list.add(i);
}
ForkJoinPool forkJoinPool = new ForkJoinPool();
// 生成一个计算任务,负责计算1+2+3+4
CountTask task = new CountTask(list);
// 执行一个任务
Future result = forkJoinPool.submit(task);
try {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("zongjieguo"+result.get());
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
}
}