Functional Programming With Java 简明教程

Functional Programming with Java - Parallelism

并行性是函数式编程的一个关键概念,其中一个大任务完成于将分解为较小独立的任务,然后这些小任务以并行方式完成,稍后组合起来给出完整的结果。随着多核处理器的出现,此技术有助于更快地执行代码。Java 有基于线程的编程支持来进行并行处理,但它相当枯燥,并且难以在没有 bug 的情况下进行实现。Java 8 及更高级,数据流有并行方法并且集合有 parallelStream() 方法来以并行方式完成任务。请参阅以下示例:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FunctionTester {
   public static void main(String[] args) {

      Integer[] intArray = {1, 2, 3, 4, 5, 6, 7, 8 };
      List<Integer> listOfIntegers = new ArrayList<>(Arrays.asList(intArray));

      System.out.println("List using Serial Stream:");
      listOfIntegers
         .stream()
         .forEach(e -> System.out.print(e + " "));
      System.out.println("");

      System.out.println("List using Parallel Stream:");
      listOfIntegers
         .parallelStream()
         .forEach(e -> System.out.print(e + " "));
      System.out.println("");

      System.out.println("List using Another Parallel Stream:");
      listOfIntegers
         .stream()
         .parallel()
         .forEach(e -> System.out.print(e + " "));
      System.out.println("");

      System.out.println("List using Parallel Stream but Ordered:");
      listOfIntegers
         .parallelStream()
         .forEachOrdered(e -> System.out.print(e + " "));
         System.out.println("");
   }
}

Output

List using Serial Stream:
1 2 3 4 5 6 7 8
List using Parallel Stream:
6 5 8 7 3 4 2 1
List using Another Parallel Stream:
6 2 1 7 4 3 8 5
List using Parallel Stream but Ordered:
1 2 3 4 5 6 7 8