说我们有这样的事情:
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",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.