溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java通過Fork/Join優(yōu)化并行計算

發(fā)布時間:2020-09-18 14:33:07 來源:腳本之家 閱讀:143 作者:FrankYou 欄目:編程語言

本文實例為大家分享了Java通過Fork/Join優(yōu)化并行計算的具體代碼,供大家參考,具體內(nèi)容如下

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反復調(diào)用fork和join直到完成。
       */
      invokeAll(new RecursiveActionDemo(source, start, split, dest), new RecursiveActionDemo(source, start + split, length - split, dest));
    }
  }
}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI