欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-06-13 08:46:04|栏目: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));
    }
  }
}

上一篇:JDK 14的新特性:文本块Text Blocks的使用

栏    目:JAVA代码

下一篇:java使用jdbc连接数据库工具类和jdbc连接mysql数据示例

本文标题:Java通过Fork/Join优化并行计算

本文地址:http://www.codeinn.net/misctech/141202.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有