我正在努力寻找一种从这个流中获得加速的正确方法:
StreamSupport.stream(new BinaryTreeSpliterator(root), true)
.parallel()
.map(node -> processor.onerousFunction(node.getValue()))
.mapToInt(i -> i.intValue())
.sum()
Run Code Online (Sandbox Code Playgroud)
onerousFunction() 只是一个使线程工作一点并返回节点的int值的函数.
无论我使用多少cpu,执行时间总是保持不变.我认为这个问题代表我写的Spliterator:
public class BinaryTreeSpliterator extends AbstractSpliterator<Node> {
private LinkedBlockingQueue<Node> nodes = new LinkedBlockingQueue<>();
public BinaryTreeSpliterator(Node root) {
super(Long.MAX_VALUE, NONNULL | IMMUTABLE);
this.nodes.add(root);
}
@Override
public boolean tryAdvance(Consumer<? super Node> action) {
Node current = this.nodes.poll();
if(current != null) {
action.accept(current);
if(current.getLeft() != null)
this.nodes.offer(current.getLeft());
if(current.getRight() != null)
this.nodes.offer(current.getRight());
return true;
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
但我真的找不到一个好的解决方案.