zoukankan      html  css  js  c++  java
  • Java通过Fork/Join来优化并行计算

    Java代码:

    package Threads;
    
    import java.util.concurrent.ForkJoinPool;
    import java.util.concurrent.RecursiveAction;
    
    /**
     * Created by Frank
     */
    public class RecursiveActionDemo extends RecursiveAction {
    
        static int[] raw = {19, 3, 0, -1, 57, 24, 65, Integer.MAX_VALUE, 42, 0, 3, 5};
        static int[] sorted = null;
        int[] source;
        int[] dest;
        int length;
        int start;
        final static int THRESHOLD = 4;
    
        public static void main(String[] args) {
            sorted = new int[raw.length];
    
            ForkJoinPool pool = new ForkJoinPool();
            pool.invoke(new RecursiveActionDemo(raw, 0, raw.length, sorted));
    
            System.out.println('[');
            for (int i : sorted) {
                System.out.println(i + ",");
            }
            System.out.println(']');
        }
    
        public RecursiveActionDemo(int[] source, int start, int length, int[] dest) {
            this.source = source;
            this.dest = dest;
            this.length = length;
            this.start = start;
        }
    
        @Override
        protected void compute() {
            System.out.println("ForkJoinDemo.compute()");
            if (length < THRESHOLD) {    // 直接计算
                for (int i = start; i < start + length; i++) {
                    dest[i] = source[i] * source[i];
                }
            } else { // 分而治之
                int split = length / 2;
                /**
                 * invokeAll反复调用fork和join直到完成。
                 */
                invokeAll(new RecursiveActionDemo(source, start, split, dest), new RecursiveActionDemo(source, start + split, length - split, dest));
            }
        }
    }
  • 相关阅读:
    百度云如何免费扩容至2055G?
    OKR学习总结
    layui和bootstrap 对比
    使用马克飞象+印象笔记 如何简单便捷地发表博客?
    Sublime使用记录之SublimeServer插件介绍
    12.RcolorBrewer包
    11.R语言流程
    25.conda 下载安装与运用
    7、purge_haplogs 基因组去冗余
    5.MCScanX 与circos下载、安装、运用
  • 原文地址:https://www.cnblogs.com/frankyou/p/6547527.html
Copyright © 2011-2022 走看看