您好,登錄后才能下訂單哦!
本文實例為大家分享了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)); } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。