说我们有这样的事情:
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.
原文地址:https://www.jb51.cc/java/125394.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。