是否可以并行运行递归函数?

问题描述

我有一个findAllPaths()函数来查找图中所有可能的路径(存储在matrix中):

    public void findAllPaths(final Matrix matrix,final Index s,final Index d,HashMap <Index,Boolean> isVisited,Collection localPathList)
    {
        // Mark the current node
        isVisited.put(s,true);
        if (s.equals(d)) {
            this.pathsList.add(new ArrayList<>(localPathList));
            // if match found no need to traverse more till depth
            isVisited.put(s,false);
            return;
        }

        // Recur for all the vertices neighbors to current index
        for (Index i : matrix.getNeighbors(s)) {
            if (!isVisited.get(i)) {
                // store current node in path[]
                localPathList.add(i);
                findAllPaths(matrix,i,d,isVisited,localPathList);
                // remove current node in path[]
                localPathList.remove(i);
            }
        }

        // Mark the current node
        isVisited.put(s,false);
    }

我正在尝试使其尽可能并行运行。

有人知道我该如何做到吗?

解决方法

您可能要使用java.util.concurrent包的RecursiveTask或RecursiveAction并在ForkjoinPool中运行它。这些类的总体思路是,您可以在代码中决定应在一个线程中完成哪部分工作。如果工作大于该部分,则将工作的一部分分叉到新线程上。要获取所有线程的结果,请使用join()。这些类使用工作窃取算法:完成一个线程后,它可以窃取另一个线程的工作,因此对于像这样的繁重运算很有效。

RecursiveTask或RecursiveAction的一个先决条件是,您应该能够将工作拆分为多个部分,并且知道如何将完成的部分组合为最终结果。大数阶乘是可以使用RecursiveTask计算的一个示例:10!可以分为(1 * 2 * 3 * 4 * 5)和(6 * 7 * 8 * 9 * 10)。可以将两个子结果相乘以获得最终结果。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...