package com.example.forkJoin;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
/**
-
@author: guozi
-
join/fork
*/
public class CountTask extends RecursiveTask {//阈值
private static final int THRESHOLD = 2;
//起始值
private long start;
//结束值
private long end;public CountTask(long start, long end) {
this.start = start;
this.end = end;
}//fork/join处理计算逻辑
@Override
protected Long compute() {boolean compute = (end - start) <= THRESHOLD; long res = 0; if (compute) {//说明长度小于阈值,不走fork/join的逻辑 for (long i = start; i <= end ; i++) { res += i; } } else { //如果长度大于阈值,则分隔为小任务 long mid = (start + end) / 2; //这里的两个任务个人理解是平分计算数据的数量 CountTask countTask1 = new CountTask(start, mid); CountTask countTask2 = new CountTask(mid + 1, end); //计算小任务的值 countTask1.fork(); countTask2.fork(); //得到两个小任务的值 long result1 = countTask1.join(); long result2 = countTask2.join(); res = result1 + result2; } return res;
}
public static void main(String[] args) throws InterruptedException,ExecutionException {
ForkJoinPool forkJoinPool = new ForkJoinPool(); long startTime1 = System.currentTimeMillis() / 1000; CountTask countTask = new CountTask(1,999999999); long endTime1 = System.currentTimeMillis() / 1000; System.out.println("fork/join 最终花费时间为: " + (endTime1 - startTime1) + " 秒"); long sum = 0L; long s1 = System.currentTimeMillis() / 1000; for (long i = 1; i <= 999999999; i++) { sum += i; } long e1 = System.currentTimeMillis() / 1000; System.out.println("sum的值为; " + sum); System.out.println("最终花费时间为: " + (e1 - s1) + " 秒"); //经过测试,submit函数是异步的 ForkJoinTask<Long> submit = forkJoinPool.submit(countTask); System.out.println("final result: " + submit.get()); if (forkJoinPool != null) { forkJoinPool.shutdown(); }
}
}
如上,为了方便大家.附上了代码,fork/join框架还是半年前才知道的知识.由于朋友是做数据分析这块,计算分工这块处理能力不错,朋友之前的查询大量数据需要13s,优化sql语句还有用上此框架后列表数据只需2S.大量缩短了时间,sql这块能力薄弱,无法帮到大家.再者,由于是简单demo,没有采用多线程的方式来处理,个人感觉此框架和future有点类似,还有java.util.current包大家有空也可以去关注下,还是有很多知识点的,楼主这边功力有限,没有一一上传,可能会抽空上传到git上.
很多是juc包里的,有很多细节点,楼主比较懒,连出来很久的jdk8目前也只是简单写了lambda表达式的
demo,大家有空也可以看下时间方面的工具类,变化有点大,由于公司用的jdk7,lambda表达式只是简化
函数用的
最后大家转载请载明楼主的地址: https://blog.csdn.net/gxx534654145/article/details/102725375