在下面的示例代码中,RecursiveSumTask类是如何利用Fork/Join框架实现并行计算的?
package learning.multithreading;
import java.util.Random;import java.util.concurrent.ExecutionException;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.RecursiveTask;
public class ParallelSumComputationUsingForkJoin { private static final int[] LARGE_ARR = largeArr();
private static final int LENGTH = LARGE_ARR.length;
public static void main(String[] args) throws ExecutionException, InterruptedException { RecursiveSumTask recursiveTask = new RecursiveSumTask(0, LENGTH, LARGE_ARR); ForkJoinPool forkJoinPool = ForkJoinPool.commonPool(); long start = System.currentTimeMillis(); long sum = forkJoinPool.invoke(recursiveTask); System.out.println("The sum is : " + sum + ", Time Taken by Parallel(Fork/Join) Execution: " + (System.currentTimeMillis() - start) + " millis"); }
private static int[] largeArr() { return new Random().ints(500000000, 10, 1000).toArray(); }
static class RecursiveSumTask extends RecursiveTask<Long> {
private static final int SEQUENTIAL_COMPUTE_THRESHOLD = 4000; private final int startIndex; private final int endIndex; private final int[] data;
RecursiveSumTask(int startIndex, int endIndex, int[] data) { this.startIndex = startIndex; this.endIndex = endIndex; this.data = data; }
@Override protected Long compute() { if (SEQUENTIAL_COMPUTE_THRESHOLD >= (endIndex - startIndex)) { long sum = 0; for (int i = startIndex; i < endIndex; i++) { sum += data[i]; } return sum; } int mid = startIndex + (endIndex - startIndex) / 2; RecursiveSumTask leftSumTask = new RecursiveSumTask(startIndex, mid, data); RecursiveSumTask rightSumTask = new RecursiveSumTask(mid, endIndex, data); leftSumTask.fork(); // Fork the Left Task in a Separate Execution long rightSum = rightSumTask.compute(); // Compute the Right Part long leftSum = leftSumTask.join(); // Wait for the results from the Left Part return leftSum + rightSum; // Return Both } }}/** * Output: * The sum is : 252235235953, Time Taken by Parallel(Fork/Join) Execution: 139 millis *
RecursiveSumTask类继承了RecursiveTask,并重写了compute()方法。当数组的大小大于设定的阈值时,任务被分为两个子任务(leftSumTask和rightSumTask),分别处理数组的左半部分和右半部分。leftSumTask被fork()到ForkJoinPool中的其他线程执行,而rightSumTask则在当前线程中执行。当两个子任务都完成后,它们的结果被合并并返回。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。