Java-Java 8并行流和自己创建线程之间的区别



我试图找出使用Java 8的parallelStream(方法1)和创建并行线程(方法2)之间的区别

我测量了使用方法1和方法2所花费的时间。但我发现了一个巨大的偏差。方法2(~700ms)比方法1(~20秒)快得多

方法1:(列表有大约100个条目)

list.parallelStream()
    .forEach(ele -> {
        //Do something.
    }));

方法2:

for(i = 0;i < 100; i++) {
    Runnable task = () -> {
     //Do something.
    }
    Thread thread = new Thread(task);
    thread.start();
}

注意:做某事是一项昂贵的操作,就像访问数据库一样。

我在两者中都添加了System.out.println()消息。我发现方法1(parallelStream)似乎是按顺序执行的,而在方法2中,消息打印得非常快。

有人能解释一下发生了什么吗。

有人能解释一下发生了什么吗。

很可能你做错了什么,但不清楚是什么。

for (int i = 0; i < 3; i++) {
    long start = System.currentTimeMillis();
    IntStream.range(0, 100).parallel()
            .forEach(ele -> {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ignored) {
                }
            });
    long time = System.currentTimeMillis() - start;
    System.out.printf("Took %,d ms to perform 100 tasks of 100 ms on %d processors%n",
            time, Runtime.getRuntime().availableProcessors());
}

打印

Took 475 ms to perform 100 tasks of 100 ms on 32 processors
Took 401 ms to perform 100 tasks of 100 ms on 32 processors
Took 401 ms to perform 100 tasks of 100 ms on 32 processors

最新更新