`
RednaxelaFX
  • 浏览: 3016643 次
  • 性别: Icon_minigender_1
  • 来自: 海外
社区版块
存档分类
最新评论

Fork-join in Java 7

    博客分类:
  • Java
阅读更多
Java theory and practice: Stick a fork in it

引用
One of the additions to the java.util.concurrent packages coming in Java™ 7 is a framework for fork-join style parallel decomposition. The fork-join abstraction provides a natural mechanism for decomposing many algorithms to effectively exploit hardware parallelism.


汗...
Java 7不愧是kitchen-sink...不过这东西看起来又挺实用的,有些时候虽然觉得(在多处理器/多核心环境下)有些地方应该开多线程来做,不过要自己管理那么多东西也确实怪麻烦的。看一例子:

引用
Listing 3. Solving the select-max problem with the fork-join framework
public class MaxWithFJ extends RecursiveAction {
    private final int threshold;
    private final SelectMaxProblem problem;
    public int result;

    public MaxWithFJ(SelectMaxProblem problem, int threshold) {
        this.problem = problem;
        this.threshold = threshold;
    }

    protected void compute() {
        if (problem.size < threshold)
            result = problem.solveSequentially();
        else {
            int midpoint = problem.size / 2;
            MaxWithFJ left = new MaxWithFJ(problem.subproblem(0, midpoint), threshold);
            MaxWithFJ right = new MaxWithFJ(problem.subproblem(midpoint + 
              1, problem.size), threshold);
            coInvoke(left, right);
            result = Math.max(left.result, right.result);
        }
    }

    public static void main(String[] args) {
        SelectMaxProblem problem = ...
        int threshold = ...
        int nThreads = ...
        MaxWithFJ mfj = new MaxWithFJ(problem, threshold);
        ForkJoinExecutor fjPool = new ForkJoinPool(nThreads);

        fjPool.invoke(mfj);
        int result = mfj.result;
    }
}


不过这东西要是能配合匿名方法/闭包来做就更简洁了。
话说,Greg Wilson很明显对这东西不感冒。一提到调试器,这并行计算的痛处就又来了一个……
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics