1
+ package edu .maskleo .module1 ;
2
+
3
+ import java .util .concurrent .ExecutionException ;
4
+ import java .util .concurrent .ForkJoinPool ;
5
+ import java .util .concurrent .Future ;
6
+ import java .util .concurrent .RecursiveTask ;
7
+
8
+ public class CountTaskForkJoinTest extends RecursiveTask <Long > {
9
+
10
+ private static final long serialVersionUID = 1L ;
11
+
12
+ //临界值
13
+ private static final int threshold = 100 ;
14
+
15
+ private long start ;
16
+ private long end ;
17
+
18
+ public CountTaskForkJoinTest (long start , long end ) {
19
+ this .start = start ;
20
+ this .end = end ;
21
+ }
22
+
23
+ /**
24
+ * ForkJoin实现,返回计算结果
25
+ *
26
+ * @param start 起始值
27
+ * @param end 结束值
28
+ * @return
29
+ * @throws InterruptedException
30
+ * @throws ExecutionException
31
+ */
32
+ private static long forkJoinTest (long start , long end ) throws InterruptedException , ExecutionException {
33
+ ForkJoinPool pool = new ForkJoinPool ();
34
+ CountTaskForkJoinTest task = new CountTaskForkJoinTest (start , end );
35
+
36
+ Future <Long > result = pool .submit (task );
37
+ return result .get ();
38
+ }
39
+
40
+ public static void main (String [] args ) throws InterruptedException , ExecutionException {
41
+ long start = System .currentTimeMillis ();
42
+ long start_index = 1 ;
43
+ long end_index = 20000 ;
44
+ long ret = forkJoinTest (start_index , end_index );
45
+ System .out .println ("result: " + ret );
46
+ long start2 = System .currentTimeMillis ();
47
+ System .out .println ("执行耗时: " + (start2 - start ));
48
+ long sum = 0L ;
49
+ for (;start_index <= end_index ;start_index ++){
50
+ sum += start_index ;
51
+ try {
52
+ Thread .sleep (1L );
53
+ }catch (Exception e ){
54
+ ;
55
+ }
56
+ }
57
+ System .out .println (sum );
58
+ System .out .println ("执行耗时: " + (System .currentTimeMillis () - start2 ));
59
+ }
60
+
61
+ /**
62
+ * 重写compute方法,判断是否将任务进行拆分计算
63
+ */
64
+ @ Override
65
+ protected Long compute () {
66
+ long sum = 0 ;
67
+ //判断是否是拆分完毕
68
+ boolean canCompute = (end - start ) <= threshold ;
69
+ if (canCompute ) {
70
+ for (long i = start ; i <= end ; i ++) {
71
+ try {
72
+ Thread .sleep (1L );
73
+ }catch (Exception e ){
74
+ ;
75
+ }
76
+ sum += i ;
77
+ }
78
+ } else {
79
+ long middle = (start + end ) / 2 ;
80
+ CountTaskForkJoinTest task1 = new CountTaskForkJoinTest (start , middle );
81
+ CountTaskForkJoinTest task2 = new CountTaskForkJoinTest (middle + 1 , end );
82
+
83
+ task1 .fork ();
84
+ task2 .fork ();
85
+
86
+ long result1 = task1 .join ();
87
+ long result2 = task2 .join ();
88
+ sum = result1 + result2 ;
89
+ }
90
+ return sum ;
91
+ }
92
+ }
0 commit comments