小编Ste*_*lvi的帖子

Java并行流:有一种导航二叉树的方法吗?

我正在努力寻找一种从这个流中获得加速的正确方法:

    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)

但我真的找不到一个好的解决方案.

java concurrency binary-tree java-stream

6
推荐指数
1
解决办法
165
查看次数

标签 统计

binary-tree ×1

concurrency ×1

java ×1

java-stream ×1