parallelStream默认使用了fork-join框架,其默认线程数是CPU核心数。
通过测试实践,发现有两种方法来修改默认的多线程数量:
1、全局设置
在运行代码之前,加入如下代码:
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "20");
2、代码块内部设置
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("线程数量:" + Thread.activeCount()); return new Random().nextInt(100) >= 0; })); try { result = fs.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e){ e.printStackTrace(); } forkJoinPool.shutdown();