自定义parallelStream的thread pool
生活随笔
收集整理的這篇文章主要介紹了
自定义parallelStream的thread pool
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 簡介
- 通常操作
- 使用自定義ForkJoinPool
- 總結(jié)
自定義parallelStream的thread pool
簡介
之前我們講到parallelStream的底層使用到了ForkJoinPool來提交任務(wù)的,默認情況下ForkJoinPool為每一個處理器創(chuàng)建一個線程,parallelStream如果沒有特別指明的情況下,都會使用這個共享線程池來提交任務(wù)。
那么在特定的情況下,我們想使用自定義的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);輸出結(jié)果:
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。
輸出結(jié)果:
INFO com.flydean.CustThreadPool - 499500總結(jié)
如果不想使用公共的線程池,則可以使用自定義的ForkJoinPool來提交。
本文的例子https://github.com/ddean2009/learn-java-streams/tree/master/stream-cust-threadpool
更多精彩內(nèi)容且看:
- 區(qū)塊鏈從入門到放棄系列教程-涵蓋密碼學(xué),超級賬本,以太坊,Libra,比特幣等持續(xù)更新
- Spring Boot 2.X系列教程:七天從無到有掌握Spring Boot-持續(xù)更新
- Spring 5.X系列教程:滿足你對Spring5的一切想象-持續(xù)更新
- java程序員從小工到專家成神之路(2020版)-持續(xù)更新中,附詳細文章教程
歡迎關(guān)注我的公眾號:程序那些事,更多精彩等著您!
更多內(nèi)容請訪問 www.flydean.com
總結(jié)
以上是生活随笔為你收集整理的自定义parallelStream的thread pool的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 8中构建无限的stream
- 下一篇: JDK14的新特性:Lombok的终结者