使用jdk8提供的lambda进行并行计算

使用jdk8提供的lambda进行并行计算

public class Demo13 {

    public static void main(String[] args) {
        List values = Arrays.asList(10, 20, 30, 40);
        /*System.out.println(add1(values));*/
        /*add2(values);*/
        add3(values);
    }

    public static int add1(List values) {
        return values.parallelStream().mapToInt(a -> a).sum();
    }

    public static void add2(List values) {
        values.parallelStream().forEach(System.out::println);
    }

    public static void add3(List values) {
        values.stream().forEach(System.out::println);
    }
}

add2使用并行流进行计算所以并不会保证输出的顺序

The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism. For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization.

查询jdk针对stream 的 forEach方法的说明,针对并行流管道,操作不会守护其各自相遇的顺序

所以结果是乱序的

30
40
20
10

如果想有顺序输出可以使用 forEachOrdered方法

你可能感兴趣的:(高并发)