并行数组算法
Arrays类提供了大量并行化操作。
Arrays.parallelSort方法可以对一个基本类型值或对象的数组排序。
java
package arrays;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;
public class ParallelSortTest {
public static void main(String[] args) throws IOException {
var contents = new String(
Files.readAllBytes(Path.of("D:\\ChromeCoreDownloads\\eclipse-jee-2024-09-R-win32-x86_64\\eclipse\\eclipse-workspace\\JavaCore1\\src\\arrays\\alice.txt")),StandardCharsets.UTF_8);
// System.out.println(contents);
String[] words = contents.split("[\\P{L}]+");
System.out.println(Arrays.toString(words));
Arrays.parallelSort(words, Comparator.comparing(String::length));
System.out.println(Arrays.toString(words));
}
}
三种:
- 默认排序:Arrays.parallelSort(words)
- 提供比较器排序:Arrays.parallelSort(words, Comparator.comparing(String::length));
- 只排序提供的范围:values.parallelSort(values.length/2,values.length);
parallelSetAll方法会用由一个函数计算得到的值填充一个数组。
java
package arrays;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;
public class ParallelSetAllTest {
public static void main(String[] args) throws IOException {
int[] values = new int[20];
Arrays.parallelSetAll(values, i->i+1);
System.out.println(Arrays.toString(values));
}
}
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
最后一个parallelPrefix方法,用一个给定结合操作的相应前缀的累加结果替换各个数组元素。
java
package arrays;
import java.util.Arrays;
public class ParallelPrefixTest {
public static void main(String[] args) {
int[] values = new int[] {1,2,3,4,5,6,7,8,9};
Arrays.parallelPrefix(values, (x,y)->x+y);
System.out.println(Arrays.toString(values));
}
}
//[1, 3, 6, 10, 15, 21, 28, 36, 45]