一分钟带你了解下java中的fork/join

https://zhuanlan.zhihu.com/p/97258195

 

作者对fork、join框架介绍得清楚;例子举得也很好,核心类都是用到了。

重要的2个类图:

 

 

 

 

配置上对应的代码

 1 public class CountTask extends RecursiveTask<Integer> {
 2     //阀值
 3     private static final int THRESHOLD = 2;
 4     private int start;
 5     private int end;
 6 
 7     public CountTask(int start, int end) {
 8         this.start = start;
 9         this.end = end;
10     }
11 
12     /**
13      * The main computation performed by this task.
14      *
15      * @return the result of the computation
16      */
17     @Override
18     protected Integer compute() {
19         int sum = 0;
20         //判断是否是拆分完毕
21         int lenth = end - start;
22         if (lenth <= THRESHOLD) {
23             //如果拆分完毕就相加
24             for (int i = start; i <= end; i++) {
25                 sum += i;
26             }
27         } else {
28             //没有拆分完毕就开始拆分
29             int middle = (start + end) / 2;
30             CountTask leftTask = new CountTask(start, middle);
31             CountTask rightTask = new CountTask(middle + 1, end);
32             //执行子任务
33             invokeAll(leftTask, rightTask);
34             //等待子任务执行完,并得到其结果
35             Integer rightResult = rightTask.join();
36             Integer leftResult = leftTask.join();
37             //合并子任务
38             sum = leftResult + rightResult;
39         }
40         return sum;
41     }
42 
43     public static void main(String[] args) throws ExecutionException, InterruptedException {
44         ForkJoinPool forkJoinPool = new ForkJoinPool();
45         CountTask countTask = new CountTask(1, 100);
46         ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(countTask);
47         System.out.println(forkJoinTask.get());
48     }
49 }

 

posted @ 2021-10-14 20:44  只要努力就不晚  阅读(356)  评论(0编辑  收藏  举报