Java Stream How to - Verify the parallel Stream








Question

We would like to know how to verify the parallel Stream.

Answer

//from w ww.jav a 2s. c  o m
import java.util.stream.IntStream;

public class Main {
  public static void main(String[] args) {
    long first = System.currentTimeMillis();
    IntStream.range(0, 4).map(a -> {
      sleep1sec();
      return a;
    }).reduce((a, b) -> a * b).ifPresent(System.out::println);

    long second = System.currentTimeMillis();
    System.out.println("time 1:" + (second - first));

    IntStream.range(0, 4).parallel().map(a -> {
      sleep1sec();
      return a;
    }).reduce((a, b) -> a * b).ifPresent(System.out::println);

    long last = System.currentTimeMillis();
    System.out.println("time 2:" + (last - second));

  }

  private static void sleep1sec() {
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
    }
  }
}

The code above generates the following result.