Java - Java 8 parallelStream与自己创建线程之间的区别

时间:2016-03-24 09:01:53

标签: java multithreading concurrency java-8 runnable

我试图找到使用Java 8的parallelStream(method1)和创建并行线程(method2)之间的区别

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

更快

方法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中,消息打印速度非常快。

任何人都可以解释发生了什么。

1 个答案:

答案 0 :(得分:0)

  

任何人都可以解释发生了什么。

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

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