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

网友投稿 202 2023-05-25


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

本文实例为大家分享了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 statSOBtyic void main(String[] args) {

sorted = new int[raw.length];

ForkJoinPool pool = new ForkJoinPool();

pool.invoke(new Recursivehttp://ActionDemo(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));

}

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java通过关闭Socket终止线程
下一篇:Java使用join方法暂停当前线程
相关文章

 发表评论

暂时没有评论,来抢沙发吧~