-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForJoinTest.java
More file actions
74 lines (60 loc) · 1.51 KB
/
ForJoinTest.java
File metadata and controls
74 lines (60 loc) · 1.51 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
package Chapter14Thread.forkJoin;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class ForJoinTest {
public static void main(String[] args) {
final int SIZE=1000;
boolean flag;
double[] numbers=new double[SIZE];
for(int i=0;i<SIZE;i++){
numbers[i]=Math.random();
}
Counter counter=new Counter(numbers, 0, numbers.length, new Filter(){
public boolean accept(double d) {
// TODO Auto-generated method stub
return d>0.8;
}
});
ForkJoinPool pool=new ForkJoinPool();
//执行
pool.invoke(counter);
//join()返回结果
System.out.println("一共有"+counter.join()+"满足条件");
}
}
interface Filter{
boolean accept(double d);
}
//将会产生一个T类型的结果
class Counter extends RecursiveTask<Integer>{
public static final int THRESHOLD=100;
private double[] values;
private int from;
private int to;
private Filter filter;
public Counter(double[] values,int from ,int to,Filter filter){
this.values=values;
this.from=from;
this.to=to;
this.filter=filter;
}
@Override
protected Integer compute() {
if(to-from<THRESHOLD){
int count=0;
//如果在from和to之间的数满足filter.accept(i),count++
for(int i=from;i<to;i++){
if(filter.accept(values[i])){
count++;
}
}
return count;
}else{
int mid=(from+to)/2;
Counter first=new Counter(values,from,mid,filter);
Counter second=new Counter(values,mid,to,filter);
this.invokeAll(first,second);
return first.join()+second.join();
}
}
}