Java 8并行流对序列使用相同的线程

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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...