-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForkJoinTest.java
More file actions
69 lines (53 loc) · 1.28 KB
/
ForkJoinTest.java
File metadata and controls
69 lines (53 loc) · 1.28 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 forkjoin;
import java.util.concurrent.*;
public class ForkJoinTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
final int SIZE=10000000;
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 x){
return x>0.5;
}
});
ForkJoinPool pool=new ForkJoinPool();
pool.invoke(counter);
System.out.println(counter.join());
}
}
interface Filter{
boolean accept(double t);
}
class Counter extends RecursiveTask<Integer>{
public static final int THRESHOLD=1000;
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;
}
protected Integer compute(){
if(to-from<THRESHOLD){
int count=0;
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);
invokeAll(first,second);
return first.join()+second.join();
}
}
}