生活随笔
收集整理的這篇文章主要介紹了
Java中的parallelStream
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、概述
Java 中的 parallelStream 的底層實(shí)現(xiàn)為 ForkJoinPool 。
線程池是所有并行流共享的。
線程池的線程數(shù)量和CPU核數(shù)一致。
需要等待任務(wù)全部執(zhí)行完畢,主線程(調(diào)用線程)才繼續(xù)往下執(zhí)行。
注意:因?yàn)榫€程池是全局共享的,所以我們盡量不要在 parallelStream 中執(zhí)行阻塞任務(wù),否則會(huì)影響到整個(gè)系統(tǒng)中其他的 parallelStream 任務(wù)執(zhí)行的。
二、案例
下面的案例中使用了2個(gè)新線程,在其中分別執(zhí)行 parallelStream 。
線程A啟動(dòng)后,我們暫停2秒,目的是為了讓線程A中的任務(wù)占滿 ForkJoinPool 中的線程,并且每個(gè)任務(wù)執(zhí)行后,要暫停10秒,目的是為了方便我們觀察 ForkJoinPool 中總共有多少個(gè)線程。
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();}}
執(zhí)行結(jié)果如下:
注意查看,首先線程A中的任務(wù)執(zhí)行了12條(包括調(diào)用線程自身),我使用的電腦CPU為12核心。
2秒鐘后,線程B開(kāi)始執(zhí)行,此時(shí)線程A中的12個(gè)線程還處于阻塞狀態(tài),線程B中的任務(wù),全部由調(diào)用線程執(zhí)行。
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
總結(jié)
以上是生活随笔為你收集整理的Java中的parallelStream的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。