RecursiveAction的应用
//通用 divide-and-conquer 并行算法的伪代码。
// PSEUDOCODE
Result solve(Problem problem) {
if (problem.size < SEQUENTIAL_THRESHOLD)
return solveSequentially(problem);
else {
Result left, right;
INVOKE-IN-PARALLEL {
left = solve(extractLeftHalf(problem));
right = solve(extractRightHalf(problem));
}
return combine(left, right);
}
}
我自己写了一个例子:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
/**
* <pre>
* @author kanpiaoxue
* Date 2013-11-29
* </pre>
*/
public class DivideAndConquer extends RecursiveAction {
private static final long serialVersionUID = 5349972192067990608L;
private final List<Integer> datas;
private final int threshold;
private int result;
public DivideAndConquer(List<Integer> datas, int level) {
super();
this.datas = datas;
this.threshold = level;
}
public static int sum(List<Integer> list) {
int sum = 0;
for (Integer i : list) {
sum += i;
}
return sum;
}
@Override
protected void compute() {
System.out
.println(Thread.currentThread().getName() + " start to work.");
if (datas.size() < threshold) {
result = sum(datas);
} else {
int toIndex = datas.size() / 2;
DivideAndConquer left = new DivideAndConquer(datas.subList(0,
toIndex), threshold);
DivideAndConquer right = new DivideAndConquer(datas.subList(
toIndex, datas.size()), threshold);
invokeAll(left, right);
result = Math.max(left.result, right.result);
}
}
public int getResult() {
return result;
}
private static List<Integer> createTestDatas(int count) {
List<Integer> list = new ArrayList<Integer>();
Random random = new Random();
for (int i = 0; i < count; i++) {
list.add(random.nextInt(1000));
}
return list;
}
/**
* @param args
*/
public static void main(String[] args) {
int count = 100000;
int level = count / 5;
List<Integer> datas = createTestDatas(count);
System.out.println("DivideAndConquer.main()");
DivideAndConquer t = new DivideAndConquer(datas, level);
ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime()
.availableProcessors() * 4);
long before = System.currentTimeMillis();
pool.invoke(t);
System.out.println("max:" + t.getResult() + ", it consumes "
+ (System.currentTimeMillis() - before) + " ms.");
}
}
更多的内容请参考:
http://www.ibm.com/developerworks/cn/java/j-lo-forkjoin/index.html