自定义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

最新文章

  1. MySQL Where 条件
  2. 学习C语言感悟
  3. Android中将xml布局文件转化为View树的过程分析(上)
  4. 【转】非常适用的Sourceinsight插件,提高效率事半功倍
  5. .NET开源项目介绍及资源推荐:数据持久层
  6. AFNetworking (3.1.0) 源码解析 &lt;六&gt;
  7. asp.net repeater控件操作
  8. jsp页面中格式化为小数点两位
  9. EasyNet.Solr 4.4.0发布及例子
  10. php实现监控在线服务应用程序小栗子
  11. Algorithm --&gt; 邮票连续组合问题
  12. linux 配置ftp服务器
  13. 和我一起熟悉caffe2
  14. scrapy中pipeline的一点综合知识
  15. .net core安装及初体验
  16. MESSAGE_TYPE_X in Badi:MB_DOCUMENT_UPDATE_BEFORE
  17. python之路——5
  18. 关于 App.config文件出错,配置系统未能初始化。 问题解决方案
  19. 牛奶ddw如何通过以太坊钱包实现互相打赏
  20. MySQL-Transfer2.3发布

热门文章

  1. jQuery学习笔记01
  2. Educational Codeforces Round 84 (Rated for Div. 2)
  3. php依赖注入与容器,Container,控制反转
  4. golang 性能测试 (1)
  5. PAT 链表倒序的算法优化
  6. P4015 运输问题【zkw费用流】
  7. istream_iterator &amp;&amp; istream_iteratorbuf
  8. Linux C++ 网络编程学习系列(7)——mbedtls编译使用
  9. std::chrono计算程序运行时间
  10. 支持向量机SVM推导