先引用<<Java 7 Concurrency Cookbook>>书中一段关于Fork Join的描述:
This framework is designed to solve problems that can be broken into smaller tasks using
the divide and conquer technique. Inside a task, you check the size of the problem you wantto resolve and, if it's bigger than an established size, you divide it in smaller tasks that are executed using the framework. If the size of the problem is smaller than the established size,you solve the problem directly in the task and then, optionally, it returns a
result. The following diagram summarizes this concept:
描述很清楚,易懂。Fork 就是把任务划分, Join就是等所有的子任务都完成后执行的合并操作。
前提就是 所谓的任务要可以拆分,比如说有求10万个数字的和,可以改成2个5万数字求和的求和,再可以分成4个2.5万数字求和的求和的求和。
就拿求和做个例子(1-100求和):
package com.javaeye.demo;
import java.util.List;
import java.util.concurrent.RecursiveTask;
public class Task extends RecursiveTask<Integer>{
private static final long serialVersionUID = 1L;
private List<Integer> numberList;
private int start;
private int end;
private int THRESHOLD = 10;
public Task(List<Integer> numberList) {
this.numberList = numberList;
start = 0;
end = this.numberList.size() - 1;
}
public Task(List<Integer> numberList, int start, int end) {
this.numberList = numberList;
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
if (end - start <= THRESHOLD) {
return sum();
} else {
int pivot = (end + start )/2;
Task task1 = new Task(numberList, start, pivot);
Task task2 = new Task(numberList, pivot+1, end);
task1.fork();
task2.fork();
return task1.join() + task2.join();
}
}
private Integer sum() {
Integer sum = 0;
for (int i = start;i <= end; i++) {
sum += this.numberList.get(i);
}
return sum;
}
}
package com.javaeye.demo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
public class Main {
public static void main(String[] args) throws Exception{
ForkJoinPool pool = new ForkJoinPool();
Task task = new Task(getData(100));
Future<Integer> result = pool.submit(task);
System.out.println(result.get());
}
private static List<Integer> getData(int len) {
List<Integer> list = new ArrayList<Integer>();
for (int i=1; i <= len; i++) {
list.add(i);
}
return list;
}
}
输出结果: 5050.
只为简单记录。