企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Java 8 - 数组并行排序 > 原文: [https://beginnersbook.com/2017/10/java-8-arrays-parallel-sort-with-example/](https://beginnersbook.com/2017/10/java-8-arrays-parallel-sort-with-example/) Java 8 在`java.util`包的`Arrays`类中引入了一个新方法`parallelSort()`。引入此方法以支持数组元素的并行排序。 并行排序算法: 1. 将给定的数组划分为子数组,将子数组进一步划分为子数组,直到子数组达到最小粒度为止。 2. 子数组由多个线程单独排序。并行排序使用 [Fork / Join Framework](https://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html) 并行地对子数组进行排序。 3. 已合并的已排序子数组。 **并行排序优于简单排序的优点:** `parallelSort()`方法使用[多线程](https://beginnersbook.com/2013/03/multithreading-in-java/)的概念,与[正常排序](https://beginnersbook.com/2014/07/how-to-sort-an-array-in-java/)相比,有很多元素时它更快。 ## 示例 1:对原始数据类型进行并行排序 ```java import java.util.Arrays; public class Example { public static void main(String[] args) { int numbers[] = {22, 89, 1, 32, 19, 5}; //Parallel Sort method for sorting int array Arrays.parallelSort(numbers); //converting the array to stream and displaying using forEach Arrays.stream(numbers).forEach(n->System.out.print(n+" ")); } } ``` 输出: ```java 1 5 19 22 32 89 ``` **参考文献:** [Java 8 - 并行排序 JavaDoc](http://download.java.net/lambda/b84/docs/api/java/util/Arrays.html#parallelSort(int[])) ## 示例 2:通过指定开始和结束索引进行并行排序 我们还可以指定排序的开始和结束,在这种情况下,从开始索引开始并在结束索引结束的子数组被排序,数组的其余部分被忽略并且不被排序。 ```java import java.util.Arrays; public class Example { public static void main(String[] args) { int numbers[] = {22, 89, 1, 32, 19, 5}; /* Specifying the start and end index. The start index is * 1 here and the end index is 5\. which means the the elements * starting from index 1 till index 5 would be sorted. */ Arrays.parallelSort(numbers, 1, 5); //converting the array to stream and displaying using forEach Arrays.stream(numbers).forEach(n->System.out.print(n+" ")); } } ``` 输出: ```java 22 1 19 32 89 5 ```