java - 等待库方法完成后再继续

标签 java multithreading

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

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/

相关文章:

c# - 计时器在跨线程中不起作用

python - FastAPI 与 pandas.read_sql() 的并行性

javascript - 应该使用多websocket连接来实现并行通信吗?

java - 使用 JAVA 从 excel 中检索 INTEGER 值

c++ - 将 thread::id 的 std::map 创建为整数值

c# - Timers Event 的委托(delegate)是否作为线程安全进程调用?

java - tomcat 8 问题不显示任何调试错误

java - 更改了DB,更新了DB版本无法添加数据也无法不添加数据

java - 如何避免很多 if else 条件

java - Spring构造函数 Autowiring 和初始化其他字段