当前位置: 移动技术网 > IT编程>开发语言>Java > Java通过Fork/Join优化并行计算

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网