"Arrays.parallelSort" method can sort an array. For example,
String contents = new String(Files.readAllBytes(Path.get("alice.txt")), StandardCharsets.UTF_8);
String[] words = contents.split("[\\P{L}]+");
Arrays.parallelSort(words);When you sort objects, you can supply a "Comparator".
Arrays.parallelSort(words, Comparator.comparing(String::length));With all methods, you can supply the bounds of a range, such as
value.parallelSort(values.length()/2, values.length());The "parallelSetAll" method fills an array with values that are computed from a function. The function receives the element index and computes the value at that position.
Arrays.parallelSetAll(values, i -> i % 10); // Fills values with 0 1 2 3 ...Finnaly, there is a "parallelPrefix" method that replaces each array element with the accumulation of the prefix for a given associative operation. Here is an example. Consider the array [1, 2, 3, ...] and the "*" operation. After executing
Arrays.parallelPrefix(values, (x, y) -> x * y);the array contains
[1, 1 * 2, 1 * 2 * 3, 1 * 2 * 3 * 4, ...]Perhaps suprisingly, this computation can be parallelized. First, join neighboring elements, , as indicated here:
[1, 1 * 2, 3, 3 * 4, 5, 5 * 6, 7, 7 * 8]The gray value are left alone. Clearly, one can make this computation in parrallel in separate regions of the array. In the next step, update the indicated elements by multiplying them with elements that are one or two position below:
[1, 1 * 2, 1 * 2 * 3, 1 * 2 * 3 * 4, 5, 5 * 6, 5 * 6 * 7, 5 * 6 * 7 * 8]This can again be done in parallel. After log(n) steps, the process is complete. This is a win over the straightforward linear computation if sufficient processors are available. On special-purpose hardware, this algorithm is commonly used, and users of such hardware are quite ingenious in adapting it to a variety of problems.
本文介绍了如何使用Java的Arrays类进行并行数组操作,包括parallelSort方法实现数组排序、parallelSetAll方法填充数组值以及parallelPrefix方法实现前缀累积计算。通过示例展示了这些方法的应用场景及其实现细节。

7145

被折叠的 条评论
为什么被折叠?



