fork-join框架

以下内容选自《JAVA核心技术卷Ⅰ》14.9.4
有些应用使用了大量线程,但其中大多数都是空闲的。举例来说,一个Web服务器可能会为每个连接分别使用一个线程。另外一些应用可能对每个处理器内核分别使用一个线程,来完成计算密集型任务,如图像或视频处理。Java SE 7中新引入了fork-join框架,专门用来支持后一类应用。

代码:

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

interface Filter{
boolean accept(double t);
}

class Counter extends RecursiveTask{
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;
}

@Override
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;
}

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();
}
}

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, (i) -> {return i > 0.5;});

ForkJoinPool pool = new ForkJoinPool();
pool.invoke(counter);
System.out.println(counter.join());
}
}

你可能感兴趣的:(java)