我有一个问题。我必须等待从库调用的方法完成才能继续我的代码。我怎样才能做到这一点?我的代码:
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 ) 得到的异常是:
Exception in thread "main" java.lang.IllegalStateException: cannot compute a distance because the two vertices are not connected
at grph.algo.distance.DistanceMatrix.getDistance(DistanceMatrix.java:56)
at 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;
}
)并填充距离矩阵。因此,如果 DistanceMatrix 尚未完成,则 getDistance(node1, node2) 方法无法从 DistanceMatrix 获取值。 我读到了关于 CountDownLatch 和 wait() 、 notify() 的内容,但我不知道如何做到这一点。有什么好的方法可以解决这个问题吗?
最佳答案
假设存在多线程问题,你就错了。
错误消息非常清楚:
(...)cannot compute a distance because the two vertices are not connected
您在图中随机选取了 2 个节点,但这些节点未连接。这就是为什么图书馆无法计算其距离的原因。
您确定没有忘记在图表中添加边吗? ;)
关于java - 等待库方法完成后再继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16390147/