【问题标题】:Wait for library method to finish before continuing等待库方法完成后再继续
【发布时间】:2013-05-05 23:21:23
【问题描述】:

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

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 中的异常:无法计算距离,因为两个顶点未连接

在 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) 方法无法从距离矩阵中获取值。 我读到了CountDownLatchwait()notify(),但我不知道该怎么做。解决这个问题的好方法是什么?

【问题讨论】:

  • path.getLength() 抛出异常是什么意思?它是 NullPointerException 还是库中的一些异常?你用的是什么库?
  • 我会先阅读库附带的文档(如果存在这样的页面,还要添加指向库网页的指针),因为这种行为确实应该在文档中进行解释。
  • 嗯?我不明白?如果函数/子系统返回一个路径,它应该在返回时有效。如果函数/子系统线程脱离了功能,因此需要稍后返回路径,它不能直接返回它。通常,某个地方会涉及到回调。
  • 我正在使用的库是:grph.inria.fr 这里是 javadoc:grph.inria.fr/javadoc/index.html 异常来自框架:线程“main”中的异常 java.lang.IllegalStateException:无法计算距离,因为这两个顶点在 grph.MatrixWrappedPath.getLength(MatrixWrappedPath.java:47) @MartinJames 的 grph.algo.distance.DistanceMatrix.getDistance(DistanceMatrix.java:56) 处没有连接,就是这种情况,函数从功能和稍后返回路径。
  • the documentation 中没有迹象表明这个函数是异步的,正如@MartinJames 所说,它也没有任何意义。所以,你在某个地方犯了一个错误或错误的假设。

标签: java multithreading


【解决方案1】:

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

错误信息很清楚:

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

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

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

【讨论】:

  • 路径存在,否则它将为空,我会得到一个 NullPointerException(来自 getShortestPath() 的 javadoc):返回:从源到目标的最短路径,如果找不到路径,则返回 null .
猜你喜欢
  • 1970-01-01
  • 2013-04-25
  • 2019-11-01
  • 2021-05-06
  • 2021-05-21
  • 2021-07-19
  • 2015-10-03
  • 2013-11-25
相关资源
最近更新 更多