- 假设想要统计一下数组中有多少个元素满足某个特定的属性。可以将这个数组一分为二,分别对这两部分进行统计,再将结果相加。
public class ForkJoinTest {
public static void main(String[] args) {
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, x -> x > 0.5);
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(counter);
System.out.println(counter.join());
}
}
class Counter extends RecursiveTask<Integer>{
//固定的线程数量
public static final int THRESHOLD = 1000;
private double[] values;
private int from;
private int to;
private DoublePredicate filter;
public Counter(double[] values, int from, int to, DoublePredicate filter) {
this.values = values;
this.from = from;
this.to = to;
this.filter = filter;
}
@Override
protected Integer compute() {
if(to - from < THRESHOLD){
int count = 0;
for(int i=from;i<to;i++){
if(filter.test(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();
}
}
}
- 在后台,Fork-join框架使用了一种有效的智能方法来平衡可用线程的工作负载,这种方法称为工作密取。每个工作线程都有一个双端队列来完成任务。一个工作线程将子任务压入其双端队列的队头。(只有一个线程可以访问队头,所以不需要加锁。)一个工作线程空闲时,它会从另一个双端队列的队尾密取一个任务。由于大的子任务都在队尾,这种密取很少出现。