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

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

public class Demo13 {

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

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

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

    public static void add3(List<Integer> 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方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值