2017-08-28 121 views
3
List<Integer> list = Arrays.asList(3, 4, 6, 1, 2, 3, 5, 6); 
list.parallelStream().forEach(System.out::print);   
list.parallelStream().map(a -> a + 2).forEach(a -> System.out.println(Thread.currentThread().getName() + "--" + a)); 

两三行会用同一个forkjoinpool吗?如果没有,如何让他们使用一个?Java8中的forkjoinpool stream api是单例吗?

回答

1

所有并行流在由ForkJoinPool.commonPool()返回的单例池中运行。例外情况是,如果您从ForkJoinPool内部运行并行流,则该流将在其调用的池中运行。

这些是在Streams API文档中没有指定的实现细节,因此java开发人员完全有权选择其他池或完全避开fork/join框架并执行其他操作。

如果知道哪些线程最终执行代码对您至关重要,那么流式API可能不是您的最佳选择。

0

目前 - 是的,有对所有默认的并行流单池 - 这是ForkJoinPool#commonPool;因此你的观察是正确的。

有一种方法可以为每个执行Stream pipeline设置自定义池,请参阅here

它看起来像这样你的第二个例子:

List<Integer> list = Arrays.asList(3, 4, 6, 1, 2, 3, 5, 6); 

    ForkJoinPool forkJoinPool = new ForkJoinPool(4); 
    ForkJoinTask<?> task = forkJoinPool.submit(() -> list 
      .parallelStream() 
      .map(a -> a + 2) 
      .forEach(a -> System.out.println(Thread.currentThread().getName() + "--" + a))); 
    task.get();