素材巴巴 > 程序开发 >

Fork/Join简单使用

程序开发 2023-09-25 15:43:30
package javaStudy.forkJoin;import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ForkJoinPool;
 import java.util.concurrent.Future;
 import java.util.concurrent.RecursiveTask;/*** Created by Clanner on 2018/2/8.* 计算任务*/
 public class CountTask extends RecursiveTask {private final int THRESHOLD = 1000;//阈值private int start;private int end;public CountTask(int start, int end) {this.start = start;this.end = end;}@Overrideprotected Integer compute() {Integer sum = 0;//如果任务足够小就计算任务boolean canCompute = (end - start) <= THRESHOLD;if (canCompute) {for (int i = start; i <= end; i++) {sum += i;}} else {//如果任务大于阈值,就分裂成两个子任务计算int middle = (start + end) / 2;CountTask leftTask = new CountTask(start, middle);CountTask rightTask = new CountTask(middle + 1, end);//执行子任务leftTask.fork();rightTask.fork();//等待子任务执行完,并得到计算结果int leftResult = leftTask.join();int rightResult = rightTask.join();//合并子任务sum = leftResult + rightResult;}return sum;}public static void main(String[] args) throws ExecutionException, InterruptedException {ForkJoinPool forkJoinPool = new ForkJoinPool();CountTask task = new CountTask(1, 100000000);long start = System.currentTimeMillis();Future result = forkJoinPool.submit(task);System.out.println("计算结果为:" + result.get() + ",共耗时" + (System.currentTimeMillis() - start) + "ms");}
 }


测试结果:







标签:

上一篇: TF 坐标变换(已整理) 下一篇:
素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。