-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestForkJoinPool.java
More file actions
69 lines (60 loc) · 1.75 KB
/
TestForkJoinPool.java
File metadata and controls
69 lines (60 loc) · 1.75 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
package com.test.concurrent;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;
public class TestForkJoinPool {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ForkJoinPool pool = ForkJoinPool.commonPool();
System.out.println("Pool init:" + pool);
ForkJoinTask<Integer> task = pool.submit(new CountTask(1, 100));
System.out.println("total:" + task.get());
try {
pool.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.out.println(e);
}
pool.shutdown();
}
static class CountTask extends RecursiveTask<Integer> {
/**
*
*/
private static final long serialVersionUID = 1L;
private int start;
private int end;
public CountTask(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
int sum = 0;
if (end - start <= 5) {
for (int i = start; i <= end; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sum += i;
}
System.out
.println(Thread.currentThread().getName() + " - sum from " + start + " to " + end + " with result " + sum);
} else {
int mid = (start + end) / 2;
CountTask leftTask = new CountTask(start, mid - 1);
CountTask rightTask = new CountTask(mid, end);
// 切分大任务
leftTask.fork();
rightTask.fork();
// 合并小任务结果
sum += leftTask.join();
sum += rightTask.join();
}
return sum;
}
}
}