我是靠谱客的博主 丰富豆芽,这篇文章主要介绍java foreach并行_java – Stream.forEach()总是并行工作吗?,现在分享给大家,希望可以做个参考。

Aggregating with Streams中,Brian Goetz比较使用Stream.collect()填充集合并使用Stream.forEach()执行相同操作,使用以下两个片段:

Set uniqueStrings = strings.stream()

.collect(HashSet::new,

HashSet::add,

HashSet::addAll);

和,

Set set = new HashSet<>();

strings.stream().forEach(s -> set.add(s));

然后他解释说:

The key

difference is that, with the forEach() version, multiple threads are trying to access a single result

container simultaneously, whereas with parallel collect(), each thread has its own local result

container, the results of which are merged afterward.

据我所知,只有当流是并行的时,多个线程才会在forEach()情况下工作.但是,在给出的示例中,forEach()在顺序流上运行(不调用parallelStream()).

那么,forEach()总是并行工作,或者代码片段应该调用parallelStream()而不是stream(). (或者我错过了什么?)

最后

以上就是丰富豆芽最近收集整理的关于java foreach并行_java – Stream.forEach()总是并行工作吗?的全部内容,更多相关java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(78)

评论列表共有 0 条评论

立即
投稿
返回
顶部