? forkjoin应该是出来很久的技术,但我从未使用过,直到上一个项目中,有个功能点对性能要求很高,如果按照单线程遍历的方法是不行。
?那就只有用分治法来实现,但在实现的过程中发现forkjoin。于是,本着“拿来主义“的精神,就去看了下。发现它刚好能满足我的需求.
?
?下面是forkjoin的简单使用,希望对需要的人提供一些帮助.
class="java">import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
public class TestForkJoinFirst extends RecursiveTask<Integer> {
private static final int minNum = 50;
private int start;
private int end;
public TestForkJoinFirst(int start,int end) {
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
int result = 0;
if ((end - start) <= minNum) {
for (int i = start; i <= end; i++) {
result += i;
}
} else {
int middle = (end + start)/ 2;
TestForkJoinFirst left = new TestForkJoinFirst(start, middle);
TestForkJoinFirst right = new TestForkJoinFirst(middle+1, end);
left.fork();
right.fork();
result = left.join() + right.join();
}
return result;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
ForkJoinPool pool = new ForkJoinPool();
Future<Integer> result = pool.submit(new TestForkJoinFirst(1, 200));
System.out.println(result.get());
}
}
?