0

我有个问题。我必须等待从库中调用的方法完成,然后才能继续我的代码。我怎样才能做到这一点?我的代码:

Random random = new Random();
int node1 = random.nextInt(graph.getNumberOfVertices() + 1);
int node2 = random.nextInt(graph.getNumberOfVertices() + 1);

MatrixWrappedPath path = graph.getShortestPath(node1, node2);
        
int pathLength = 0;
if (path != null) {
    pathLength = path.getLength();
}

我从图书馆(http://grph.inria.fr/javadoc/index.html)得到的例外是:

线程“主”java.lang.IllegalStateException 中的异常:无法计算距离,因为两个顶点未连接

在 grph.algo.distance.DistanceMatrix.getDistance(DistanceMatrix.java:56)

在 grph.MatrixWrappedPath.getLength(MatrixWrappedPath.java:47)

DistanceMatrix 类运行一个 BFS (org.dipergrafs.algo.bfs.BFSAlgorithm),它是多线程的 (org.dipergrafs.algo.SingleSourceSearchAlgorithm,方法“compute”:

public R[] compute(final Grph g, IntSet sources)
{
final R[] r = createArray(sources.getGreatest() + 1);

new MultiThreadProcessing(g.getVertices(), Grph.getNumberOfThreadsToCreate()) {

    @Override
    protected void run(int threadID, int source)
    {
    r[source] = compute(g, source);
    }

};

return r;
}

) 并填充距离矩阵。因此,如果距离矩阵尚未完成,则 getDistance(node1, node2) 方法无法从距离矩阵中获取值。我阅读了CountDownLatchand wait(), notify(),但我不知道如何做到这一点。什么是解决这个问题的好方法?

4

1 回答 1

1

假设那里存在多线程问题,您就错了。

错误信息非常清楚:

(...)cannot compute a distance because the two vertices are not connected 

您在图中采用 2 个随机节点,但这些节点未连接。这就是图书馆无法计算其距离的原因。

你确定你没有忘记在你的图表中添加边吗?;)

于 2013-05-06T12:58:31.317 回答