parallelStream默認(rèn)使用了fork-join框架,其默認(rèn)線程數(shù)是CPU核心數(shù)蔓倍。
有兩種方法來修改默認(rèn)的多線程數(shù)量:
1客蹋、全局設(shè)置
在運(yùn)行代碼之前,加入如下代碼:
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "20");
2匹表、代碼塊內(nèi)部設(shè)置
ForkJoinPool forkJoinPool1 = new ForkJoinPool(20);
ForkJoinTask<Boolean> fs = forkJoinPool.submit(() -> inputStream.allMatch(element -> {
Thread.sleep(300);
System.out.println(Thread.currentThread().getName());
System.out.println("線程數(shù)量:" + Thread.activeCount());
return new Random().nextInt(100) >= 0;
}));
try {
result = fs.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e){
e.printStackTrace();
}
forkJoinPool.shutdown();