一、概述
Fork:把一个复杂任务进行分拆,大事化小,Join:把分拆任务的结果进行合并
二、相关类
2.1、ForkJoinPool
分支合并池,类比线程池。
2.2、ForkJoinTask
ForkJoinTask,类比 FutureTask。
2.3、RecursiveTask
递归任务:继承后可以实现递归(自己调自己)调用的任务
2.4、案例代码
2.4.1、MyRecursiveTask
/*** @Author : 一叶浮萍归大海* @Date: 2023/11/21 10:10* @Description:*/
public class MyRecursiveTask extends RecursiveTask<Integer> {private static final Integer ADJUST_VALUE = 10;private int begin;private int end;private int result;public MyRecursiveTask(int begin, int end) {this.begin = begin;this.end = end;}@Overrideprotected Integer compute() {if ((end - begin) <= ADJUST_VALUE) {for (int i = begin; i <= end; i++) {result += i;}System.out.println("(end - begin) result : " + result);} else {int middle = (begin + end) / 2;MyRecursiveTask task1 = new MyRecursiveTask(begin, middle);MyRecursiveTask task2 = new MyRecursiveTask(middle + 1, end);task1.fork();task2.fork();result = task1.join() + task2.join();System.out.println("(end + begin)/2 result : " + result);}return result;}
}
2.4.2、RecursiveTaskMainApp
/*** @Author : 一叶浮萍归大海* @Date: 2023/11/21 10:12* @Description: 分支合并案例代码*/
public class RecursiveTaskMainApp {public static void main(String[] args) throws ExecutionException, InterruptedException {MyRecursiveTask task = new MyRecursiveTask(1,100);ForkJoinPool forkJoinPool = new ForkJoinPool();ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(task);System.out.println(forkJoinTask.get());forkJoinPool.shutdown();}}