使用Java多路搜索树的fork-join多路、Java、join、fork

2023-09-11 05:29:22 作者:装不下

我多路树形结构,这是我穿越到确定状态。我期待到那里的叶节点首先处理后序式的穿越。和搜索结束条件取决于有任何不活动状态的子节点。此外,从性能的角度来看,我会用JDK7的的fork-join机制。

I have multi-way tree structure, which i have to traverse to determine status. I am looking into 'Post-Order' type traversal where leaf nodes are processed first. And search end condition depends on any of child node having status inactive. Also, from performance perspective, i would to use JDK7's fork-join mechanism.

推荐答案

下面是你如何能做到这一点(非常)的草图。

Here is a (very) rough sketch of how you could do it.

final class TreeNode {
    private final Iterable<TreeNode> children;

    TreeNode(Iterable<TreeNode> aChildren) {
        children = aChildren;
    }

    Iterable<TreeNode> getChildren() {
        return children;
    }

    void postorder(TreeNodeIterator iterator) {
        postorderTraverse(this, iterator);
    }

    private void postorderTraverse(TreeNode node, TreeNodeIterator iterator) {
        for (TreeNode child : children) {
            postorderTraverse(child, iterator);
        }
        iterator.visit(node);
    }

    void postorderParallel(TreeNodeIterator iterator) {
        new ForkJoinPool().invoke(new VisitNodeAction(iterator, this));
    }

    interface TreeNodeIterator {
        void visit(TreeNode child);
    }

    private class VisitNodeAction extends RecursiveAction {
        private final TreeNodeIterator iterator;
        private final TreeNode node;

        private VisitNodeAction(TreeNodeIterator iterator, TreeNode node) {
            this.iterator = iterator;
            this.node = node;
        }

        @Override
        protected void compute() {
            List<RecursiveAction> tasks = new LinkedList<RecursiveAction>();
            for (TreeNode child : children) {
                tasks.add(new VisitNodeAction(iterator, child));
            }
            invokeAll(tasks);
            iterator.visit(node);
        }
    }
}

有些事情,就需要修改:

Some things that would need to be modified:

添加您检查状态处于非活动状态。最简单的方法是将保持在每一个原子布尔 RecursiveAction 正在处理节点之前检查并当一个节点是不活动的更新,虽然这不是一个非常干净的或功能性的路线 添加的方式来决定何时应该使用新的线程,上述使用一个线程为每个节点。此外,您可能会因不能在 postorderParallel 的每次调用创建一个 ForkJoinPool 优化它一下。 Adding your check for the status being inactive. Easiest way would be to keep a atomic boolean in each RecursiveAction that is checked before processing the node and updated when a node is inactive, although this is not a very clean or functional route. Adding a way to decide when new threads should be used, the above uses a thread for every node. Also, you could possibly optimize it a bit by not creating a ForkJoinPool on every invocation of postorderParallel.