gpt4 book ai didi

java - 并行化简操作

转载 作者:行者123 更新时间:2023-11-30 02:19:34 26 4
gpt4 key购买 nike

是否可以通过简单地将流更改为并行流,将如下常见的“最大”操作作为归约操作分布在多个内核上?
不同线程的结果之间如何进行最终协调(没有显式组合器)?

List<Employee> emps = new ArrayList<>();
emps.add(new Employee("Roy1",32));
emps.add(new Employee("Roy2",12));
emps.add(new Employee("Roy3",22));
emps.add(new Employee("Roy4",42));
emps.add(new Employee("Roy5",52));

Integer maxSal= emps.parallelStream().mapToInt(e -> e.getSalary()).reduce((a,b)->Math.max(a, b)).getAsInt();

System.out.println("Maximum in parallel " + maxSal);

最佳答案

是的,reduce 可以并行化。但是,这需要您传递关联运算符。摘自java.util.stream JavaDoc:

Associativity

An operator or function op is associative if the following holds:

(a op b) op c == a op (b op c)

The importance of this to parallel evaluation can be seen if we expand this to four terms:

a op b op c op d == (a op b) op (c op d)

So we can evaluate (a op b) in parallel with (c op d), and then invoke op on the results. Examples of associative operations include numeric addition, min, and max, and string concatenation.

关于java - 并行化简操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47257572/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com