生活随笔
收集整理的這篇文章主要介紹了
Java中的parallelStream
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、概述
Java 中的 parallelStream 的底層實現為 ForkJoinPool 。
線程池是所有并行流共享的。
線程池的線程數量和CPU核數一致。
需要等待任務全部執行完畢,主線程(調用線程)才繼續往下執行。
注意:因為線程池是全局共享的,所以我們盡量不要在 parallelStream 中執行阻塞任務,否則會影響到整個系統中其他的 parallelStream 任務執行的。
二、案例
下面的案例中使用了2個新線程,在其中分別執行 parallelStream 。
線程A啟動后,我們暫停2秒,目的是為了讓線程A中的任務占滿 ForkJoinPool 中的線程,并且每個任務執行后,要暫停10秒,目的是為了方便我們觀察 ForkJoinPool 中總共有多少個線程。
public static void main(String[] args
) {try {List list
= new ArrayList<>(20);for (int i
= 0; i
< 20; i
++) {list
.add(i
);}Thread t_A
= new Thread(() -> {list
.parallelStream().forEach((i
) -> {System.out
.println(i
+ "=====A=====" + Thread.currentThread().getName());try {Thread.sleep(10000);} catch (InterruptedException e
) {e
.printStackTrace();}});});t_A
.start();Thread.sleep(2000);Thread t_B
= new Thread(() -> {list
.parallelStream().forEach((i
) -> {System.out
.println(i
+ "=====B=====" + Thread.currentThread().getName());});});t_B
.start();t_A
.join();t_B
.join();} catch (InterruptedException e
) {e
.printStackTrace();}}
執行結果如下:
注意查看,首先線程A中的任務執行了12條(包括調用線程自身),我使用的電腦CPU為12核心。
2秒鐘后,線程B開始執行,此時線程A中的12個線程還處于阻塞狀態,線程B中的任務,全部由調用線程執行。
12=====A=====Thread-0
6=====A=====ForkJoinPool.commonPool
-worker
-9
7=====A=====ForkJoinPool.commonPool
-worker
-6
2=====A=====ForkJoinPool.commonPool
-worker
-2
8=====A=====ForkJoinPool.commonPool
-worker
-11
4=====A=====ForkJoinPool.commonPool
-worker
-4
5=====A=====ForkJoinPool.commonPool
-worker
-15
1=====A=====ForkJoinPool.commonPool
-worker
-13
3=====A=====ForkJoinPool.commonPool
-worker
-8
9=====A=====ForkJoinPool.commonPool
-worker
-1
0=====A=====ForkJoinPool.commonPool
-worker
-10
17=====A=====ForkJoinPool.commonPool
-worker
-3
12=====B=====Thread-1
14=====B=====Thread-1
13=====B=====Thread-1
11=====B=====Thread-1
10=====B=====Thread-1
17=====B=====Thread-1
19=====B=====Thread-1
18=====B=====Thread-1
16=====B=====Thread-1
15=====B=====Thread-1
6=====B=====Thread-1
5=====B=====Thread-1
8=====B=====Thread-1
9=====B=====Thread-1
7=====B=====Thread-1
2=====B=====Thread-1
4=====B=====Thread-1
3=====B=====Thread-1
1=====B=====Thread-1
0=====B=====Thread-1
13=====A=====ForkJoinPool.commonPool
-worker
-11
18=====A=====ForkJoinPool.commonPool
-worker
-3
15=====A=====ForkJoinPool.commonPool
-worker
-9
10=====A=====ForkJoinPool.commonPool
-worker
-4
19=====A=====ForkJoinPool.commonPool
-worker
-10
16=====A=====ForkJoinPool.commonPool
-worker
-1
11=====A=====ForkJoinPool.commonPool
-worker
-13
14=====A=====ForkJoinPool.commonPool
-worker
-8
總結
以上是生活随笔為你收集整理的Java中的parallelStream的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。