温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java通过Fork/Join优化并行计算

发布时间:2020-09-18 14:33:07 来源:脚本之家 阅读:132 作者:FrankYou 栏目:编程语言

本文实例为大家分享了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));
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI