ForkJoin

ForkJoin

什么是ForkJoin?

并行执行任务,提交效率,大数据量的时候使用!

把大任务拆分成小任务

ForkJoin特点:工作窃取

内部维护的双端队列,两端都可以出

如何使用

  1. 创建ForkJoinPool对象
  2. 新建一个计算任务ForkJoinTask放入池子中计算
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.lizhi;

import java.util.concurrent.RecursiveTask;

public class ForkJoinDemo extends RecursiveTask<Long> {
private long start;
private long end;
private long temp = 10000L;

public ForkJoinDemo(long start, long end) {
this.start = start;
this.end = end;
}

@Override
public Long compute(){
long result = 0;
if(end-start<temp){
for (long i = start; i <= end; i++) {
result+=i;
}
}else {
long middle = (start + end) / 2;
ForkJoinDemo forkJoinDemo1 = new ForkJoinDemo(start,middle);
forkJoinDemo1.fork();
ForkJoinDemo forkJoinDemo2 = new ForkJoinDemo(middle,end);
forkJoinDemo2.fork();//把任务压入线程队列
result = forkJoinDemo1.join()+ forkJoinDemo2.join();
}
return result;
}
}
给作者买杯咖啡吧~~~