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