假设我们有这样的东西:
LongStream.range(0, 10).parallel()
.filter(l -> {
System.out.format("filter: %s [%s]\n", l, Thread.currentThread().getName());
return l % 2 == 0;
})
.map(l -> {
System.out.format("map: %s [%s]\n", l, Thread.currentThread().getName());
return l;
});
如果你运行这个程序输出会是这样的:
filter: 6 [main]
map: 6 [main]
filter: 5 [main]
filter: 4 [ForkJoinPool.commonPool-worker-2]
map: 4 [ForkJoinPool.commonPool-worker-2]
filter: 1 [ForkJoinPool.commonPool-worker-3]
filter: 2 [ForkJoinPool.commonPool-worker-1]
filter: 0 [ForkJoinPool.commonPool-worker-3]
filter: 3 [ForkJoinPool.commonPool-worker-2]
filter: 8 [main]
filter: 7 [ForkJoinPool.commonPool-worker-2]
filter: 9 [ForkJoinPool.commonPool-worker-2]
map: 0 [ForkJoinPool.commonPool-worker-3]
map: 2 [ForkJoinPool.commonPool-worker-1]
map: 8 [main]`
正如我们所见,每个 long 的每个任务序列都由同一个线程执行。这是我们可以依靠的东西,还是只是巧合?线程可以在执行期间“共享”任务吗?
最佳答案
来自 stream package summary关于副作用的部分:
If the behavioral parameters do have side-effects, unless explicitly stated, there are no guarantees as to the visibility of those side-effects to other threads, nor are there any guarantees that different operations on the "same" element within the same stream pipeline are executed in the same thread.
关于java - Java 8 并行流是否对序列使用相同的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36609417/