The first excerpt about collection concurrency:
One difficulty in implementing parallelism in applications so use collections was that collections be not Thread-safe, W Hich means that multiple threads cannot manipulate a collection without introducing thread interference or memory consiste ncy errors. The collections Framework provides synchronization wrappers, which add automatic synchronization to an arbitrary collectio N, 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 th At your do not modify the collection while you are operating on it.
This passage can explain why you need to parallel stream.
Here's a look at how to use the parallel stream, with two ways to call it:
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 ();
There is also a question about sorting, the following code using Foreachordered can be guaranteed order, with the general foreach is not guaranteed order:
Listofintegers . Parallelstream () . foreachordered (E-System.out.print (E + ""));
Java Parallel Stream Usage