Java parallel stream用法

先摘錄關於collection併發的一段話:html

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.java

這段話可以說明爲何須要parallel stream.併發

下面看看如何使用parallel stream,有兩種調用方式:oracle

1.app

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

  

2.ide

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

  

還有個關於排序的問題,下面這段代碼使用forEachOrdered是能保證順序的,用通常的forEach是沒法保證順序的:spa

listOfIntegers
    .parallelStream()
    .forEachOrdered(e -> System.out.print(e + " "));
相關文章
相關標籤/搜索