博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【转】Fork/Join框架测试
阅读量:5270 次
发布时间:2019-06-14

本文共 2777 字,大约阅读时间需要 9 分钟。

Fork/Join框架介绍

下面使用该框架计算0-50000000000的和,并比较普通计算方法、Fork/Join框架、Java8新特性三种计算方式的计算时间:

1 import java.time.Duration; 2 import java.time.Instant; 3 import java.util.concurrent.ForkJoinPool; 4 import java.util.concurrent.ForkJoinTask; 5 import java.util.concurrent.RecursiveTask; 6 import java.util.stream.LongStream; 7  8 import org.junit.Test; 9 10 public class TestForkJoinPool {11 12     public static void main(String[] args) {13         Instant start = Instant.now();14         ForkJoinPool pool = new ForkJoinPool();15         ForkJoinTask
task = new ForkJoinSumCalculate(0L, 50000000000L);16 Long sum = pool.invoke(task);17 System.out.println(sum);18 Instant end = Instant.now();19 System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());//1059020 }21 22 @Test23 public void test1(){24 Instant start = Instant.now();25 long sum = 0L;26 for (long i = 0L; i <= 50000000000L; i++) {27 sum += i;28 }29 System.out.println(sum);30 Instant end = Instant.now();31 System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());//1570432 }33 34 //java8 新特性35 @Test36 public void test2(){37 Instant start = Instant.now();38 Long sum = LongStream.rangeClosed(0L, 50000000000L)39 .parallel()40 .reduce(0L, Long::sum);41 System.out.println(sum);42 Instant end = Instant.now();43 System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());//811844 }45 }46 47 class ForkJoinSumCalculate extends RecursiveTask
{48 49 private static final long serialVersionUID = -259195479995561737L;50 51 private long start;52 private long end;53 private static final long THURSHOLD = 10000L; //临界值54 public ForkJoinSumCalculate(long start, long end) {55 this.start = start;56 this.end = end;57 }58 59 @Override60 protected Long compute() {61 long length = end - start;62 if(length <= THURSHOLD){63 long sum = 0L;64 for (long i = start; i <= end; i++) {65 sum += i;66 }67 return sum;68 }else{69 long middle = (start + end) / 2;70 ForkJoinSumCalculate left = new ForkJoinSumCalculate(start, middle); 71 left.fork(); //进行拆分,同时压入线程队列72 ForkJoinSumCalculate right = new ForkJoinSumCalculate(middle+1, end);73 right.fork(); //74 return left.join() + right.join();75 }76 }77 }

 转载自:http://blog.csdn.net/xiangwanpeng/article/details/54977709

转载于:https://www.cnblogs.com/ccfdod/p/6414676.html

你可能感兴趣的文章
课后作业-阅读任务-阅读笔记-3
查看>>
喜欢种种“开放平台”
查看>>
6.00.1x Introduction to computation
查看>>
阅读《名师讲坛--Android开发实战经典》
查看>>
php rsa加密解密实例
查看>>
【转】用perl写的单位电脑信息采集程序
查看>>
mysql install
查看>>
typescript - 9.装饰器
查看>>
西北大学2019春季校赛填坑笔记
查看>>
每天干的啥?(2018.03)
查看>>
Objective - C基础: 第六天 - 1.ARC自动引用计数的基本认识
查看>>
python中os和sys模块的详解
查看>>
C# struct class 在Marshal.SizeOf 的区别
查看>>
python初步(附学习思维导图)
查看>>
sql 中实现取得汉字首写字母
查看>>
git push解决办法: ! [remote rejected] master -> master (pre-receive hook declined)
查看>>
XCode快捷键
查看>>
Objective-C——关联对象
查看>>
2-sat
查看>>
Java知多少(69)面向字节的输入输出流
查看>>