加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 16:26:46 所属栏目:Java 来源:网络整理
导读:说我们有这样的事情: 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
说我们有这样的事情:
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读