自定义parallelStream的thread pool
2024-09-03 15:16:22
自定义parallelStream的thread pool
简介
之前我们讲到parallelStream的底层使用到了ForkJoinPool来提交任务的,默认情况下ForkJoinPool为每一个处理器创建一个线程,parallelStream如果没有特别指明的情况下,都会使用这个共享线程池来提交任务。
那么在特定的情况下,我们想使用自定义的ForkJoinPool该怎么处理呢?
通常操作
假如我们想做一个从1到1000的加法,我们可以用并行stream这样做:
List<Integer> integerList= IntStream.range(1,1000).boxed().collect(Collectors.toList());
ForkJoinPool customThreadPool = new ForkJoinPool(4);
Integer total= integerList.parallelStream().reduce(0, Integer::sum);
log.info("{}",total);
输出结果:
INFO com.flydean.CustThreadPool - 499500
使用自定义ForkJoinPool
上面的例子使用的共享的thread pool。 我们看下怎么使用自定义的thread pool来提交并行stream:
List<Integer> integerList= IntStream.range(1,1000).boxed().collect(Collectors.toList());
ForkJoinPool customThreadPool = new ForkJoinPool(4);
Integer actualTotal = customThreadPool.submit(
() -> integerList.parallelStream().reduce(0, Integer::sum)).get();
log.info("{}",actualTotal);
上面的例子中,我们定义了一个4个线程的ForkJoinPool,并使用它来提交了这个parallelStream。
输出结果:
INFO com.flydean.CustThreadPool - 499500
总结
如果不想使用公共的线程池,则可以使用自定义的ForkJoinPool来提交。
本文的例子https://github.com/ddean2009/learn-java-streams/tree/master/stream-cust-threadpool
欢迎关注我的公众号:程序那些事,更多精彩等着您!
更多内容请访问 www.flydean.com
最新文章
- MySQL Where 条件
- 学习C语言感悟
- Android中将xml布局文件转化为View树的过程分析(上)
- 【转】非常适用的Sourceinsight插件,提高效率事半功倍
- .NET开源项目介绍及资源推荐:数据持久层
- AFNetworking (3.1.0) 源码解析 <;六>;
- asp.net repeater控件操作
- jsp页面中格式化为小数点两位
- EasyNet.Solr 4.4.0发布及例子
- php实现监控在线服务应用程序小栗子
- Algorithm -->; 邮票连续组合问题
- linux 配置ftp服务器
- 和我一起熟悉caffe2
- scrapy中pipeline的一点综合知识
- .net core安装及初体验
- MESSAGE_TYPE_X in Badi:MB_DOCUMENT_UPDATE_BEFORE
- python之路——5
- 关于 App.config文件出错,配置系统未能初始化。 问题解决方案
- 牛奶ddw如何通过以太坊钱包实现互相打赏
- MySQL-Transfer2.3发布
热门文章
- jQuery学习笔记01
- Educational Codeforces Round 84 (Rated for Div. 2)
- php依赖注入与容器,Container,控制反转
- golang 性能测试 (1)
- PAT 链表倒序的算法优化
- P4015 运输问题【zkw费用流】
- istream_iterator &;&; istream_iteratorbuf
- Linux C++ 网络编程学习系列(7)——mbedtls编译使用
- std::chrono计算程序运行时间
- 支持向量机SVM推导