码迷,mamicode.com
首页 > 编程语言 > 详细

Java parallel stream用法

时间:2017-10-06 11:34:07      阅读:396      评论:0      收藏:0      [点我收藏+]

标签:cannot   为什么   ant   hat   cin   logs   ase   wrapper   and   

先摘录关于collection并发的一段话:

One difficulty in implementing parallelism in applications that use collections is that collections are not thread-safe, which means that multiple threads cannot manipulate a collection without introducing thread interference or memory consistency errors. The Collections Framework provides synchronization wrappers, which add automatic synchronization to an arbitrary collection, making it thread-safe. However, synchronization introduces thread contention. You want to avoid thread contention because it prevents threads from running in parallel. Aggregate operations and parallel streams enable you to implement parallelism with non-thread-safe collections provided that you do not modify the collection while you are operating on it.

这段话能够说明为什么需要parallel stream.

下面看看如何使用parallel stream,有两种调用方式:

1.

double average = roster
    .parallelStream()
    .filter(p -> p.getGender() == Person.Sex.MALE)
    .mapToInt(Person::getAge)
    .average()
    .getAsDouble();

  

2.

double average = roster
    .stream().parallel()
    .filter(p -> p.getGender() == Person.Sex.MALE)
    .mapToInt(Person::getAge)
    .average()
    .getAsDouble();

  

还有个关于排序的问题,下面这段代码使用forEachOrdered是能保证顺序的,用一般的forEach是无法保证顺序的:

listOfIntegers
    .parallelStream()
    .forEachOrdered(e -> System.out.print(e + " "));

  

Java parallel stream用法

标签:cannot   为什么   ant   hat   cin   logs   ase   wrapper   and   

原文地址:http://www.cnblogs.com/huangzifu/p/7631164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!