我有问题。在继续我的代码之前,我必须等待我从库中调用的方法才能完成。我怎样才能做到这一点?我的代码:
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)是:
线程“main”中的异常java.lang.IllegalStateException:无法计算距离,因为两个顶点未连接
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。因此,如果DistanceMatrix尚未完成,则getDistance(node1,node2)方法无法从DistanceMatrix获取值。
我读到了CountDownLatch
和wait()
,notify()
,但我无法弄清楚如何做到这一点。什么是解决这个问题的好方法?
答案 0 :(得分:1)
当假设存在多线程问题时,你错了。
错误信息非常明确:
(...)cannot compute a distance because the two vertices are not connected
您在图表中占用了2个随机节点,但这些节点未连接。这就是图书馆无法计算距离的原因。
您确定没有忘记在图表中添加边缘吗? ;)