欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-02 18:23:16
本文实例为大家分享了java通过fork/join优化并行计算的具体代码,供大家参考,具体内容如下 java代码: package threads; im...

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

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