本文实例为大家分享了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)); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
【java基础】面试常见问题:类和对象,封装继承多态,final关键字,static关键字,类加载过程,双亲委派模型
荐 Java语言基础之JDK1.8新特性(Lambda表达式、函数式接口、Stream流、新的日期API)
网友评论