java 8流和并行流之间的区别 [英] Difference between java 8 streams and parallel streams

查看:169
本文介绍了java 8流和并行流之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用java 8流和并行流编写代码以获得与自定义收集器相同的功能来执行聚合功能。
当我使用 htop 查看CPU使用情况时,它显示了用于流和并行流版本的所有CPU核心。因此,当使用 list.stream()时,它似乎也使用所有CPU。在这里, parallelStream() stream()多核的使用方面的精确差异是什么?

I wrote code using java 8 streams and parallel streams for the same functionality with a custom collector to perform an aggregation function. When I see CPU usage using htop, it shows all CPU cores being used for both `streams' and 'parallel streams' version. So, it seems when list.stream() is used, it also uses all CPUs. Here, what is the precise difference between parallelStream() and stream() in terms of usage of multi-core.

推荐答案

考虑以下计划:

import java.util.ArrayList;
import java.util.List;

public class Foo {
    public static void main(String... args) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            list.add(i);
        }
        list.stream().forEach(System.out::println);
    }
}

你会注意到这个程序将从中输出数字按顺序排列0到999,按照它们在列表中的顺序排列。如果我们将 stream()更改为 parallelStream()这不再是这种情况(至少在我的计算机上):所有号码都是写的,但顺序不同。所以,显然, parallelStream()确实使用了多个线程。

You will notice that this program will output the numbers from 0 to 999 sequentially, in the order in which they are in the list. If we change stream() to parallelStream() this is not the case anymore (at least on my computer): all number are written, but in a different order. So, apparently, parallelStream() indeed uses multiple threads.

htop 的原因在于,即使是单线程应用程序也被大多数现代操作系统划分为多个核心(同一个线程的部分可能在多个核心上运行,但当然不能同时运行)。因此,如果您发现某个进程使用了​​多个核心,则这并不意味着该程序必须使用多个线程。

The htop is explained by the fact that even single-threaded applications are divided over mutliple cores by most modern operating systems (parts of the same thread may run on several cores, but of course not at the same time). So if you see that a process used more than one core, this does not mean necessarily that the program uses multiple threads.

使用多个线程时,性能也可能无法提高。同步的成本可能会增加使用多线程的收益。对于简单的测试场景,通常就是这种情况。例如,在上面的示例中, System.out 已同步。因此,尽管使用了多个线程,但实际上只能同时写入数字。

Also the performance may not improve when using multiple threads. The cost of synchronization may nihilite the gains of using multiple threads. For simple testing scenarios this is often the case. For example, in the above example, System.out is synchronized. So, effectively, only number can be written at the same time, although multiple threads are used.

这篇关于java 8流和并行流之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆