1.ForkJoinWorkerThread:执行ForkJoin任务的线程。
2.ForkJoinPool:管理执行ForkJoin任务线程的线程池
3.ForkJoinTask:ForkJoinPool中的任务
- RecursiveAction 一个递归无结果的ForkJoinTask(没有返回值)
- RecursiveTask 一个递归有结果的ForkJoinTask(有返回值)
Task类:
import java.util.concurrent.RecursiveTask;
public class MyForkJoinTask extends RecursiveTask<Integer> {
public MyForkJoinTask(int[] nums,int start,int end){
this.nums=nums;
this.start=start;
this.end=end;
}
//每个线程分配执行的任务数 <=limit
private int limit = 10;
//开始位置
private int start;
//结束位置
private int end;
//任务列队
public int[] nums;
@Override
protected Integer compute() {
System.out.println(Thread.currentThread().getName()+":::执行"+start+"到"+end);
int sum = 0;
//断点时start一直为0
if(end-start<=limit){
for (int i = start; i < end; i++) {
sum+=nums[i];
}
} else {
int middle = (start+end)/2;
MyForkJoinTask left = new MyForkJoinTask(nums,start,middle);
MyForkJoinTask right = new MyForkJoinTask(nums,middle,end);
left.fork();right.fork();
//获得结果
sum = left.join()+right.join();
}
return sum;
}
}
main类
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//放入100个1
int amount = 100;
int[] nums=new int[amount];
for (int i = 0; i < amount; i++) {
nums[i]=i+1;
}
MyForkJoinTask myForkJoinTask = new MyForkJoinTask(nums,0,nums.length);
ForkJoinPool forkJoinPool = new ForkJoinPool();
//100个1进行相加
forkJoinPool.submit(myForkJoinTask);
int sum = myForkJoinTask.get();
System.out.println(sum);
}
}