-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForkJoinDemo.java
More file actions
79 lines (63 loc) · 2.12 KB
/
Copy pathForkJoinDemo.java
File metadata and controls
79 lines (63 loc) · 2.12 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package forkjoin;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
/**
* @author : CodeWater
* @create :2022-06-03-20:50
* @Function Description :分支合并操作:1+2+。。。+100,分成多个子任务进行
*/
class MyTask extends RecursiveTask<Integer>{
//拆分差值不能超过10,计算10以内运算
private static final Integer VALUE = 10;
//拆分开始值
private int begin;
//拆分结束值
private int end ;
//返回结果
private int result ;
//创建有参数构造
public MyTask( int begin , int end ){
this.begin = begin;
this.end = end;
}
//拆分和合并过程
@Override
protected Integer compute(){
//判断相加两个数值是否大于10
if( end - begin <= VALUE ){
//相加操作
for( int i = begin ; i <= end ; i++ ){
result = result + i;
}
}else{//进一步拆分
//获取中间值
int middle = ( begin + end ) / 2;
//拆分左边
MyTask task01 = new MyTask( begin , middle );
//拆分右边
MyTask task02 = new MyTask( middle + 1 , end );
//调用方法拆分
task01.fork();
task02.fork();
//合并结果
result = task01.join() + task02.join();
}
return result;
}
}
public class ForkJoinDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建MyTask对象
MyTask myTask = new MyTask( 0 , 100 );
//创建分支合并池对象
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit( myTask );
//获取最终合并之后结果
Integer result = forkJoinTask.get();
System.out.println( result );
//关闭池对象
forkJoinPool.shutdown();
}
}