java - 在再次循环之前等待循环内的方法完成
问题描述
我正在构建一个 java fx 应用程序并在它自己的线程上有一个 while 循环,但循环不会等待 Dijkstra 方法返回一个数组,我似乎通过将线程休眠 1000 毫秒暂时解决了这个问题,但我没有真的不知道为什么会这样,但是有没有更好的方法让我可以等待方法完成然后开始下一次迭代?
public class Chasers {
public volatile List<List<Integer>> Path; ///////
volatile int ChaserX;
volatile int ChaserY;
volatile int PlayerX;
volatile int PlayerY;
boolean Continue=true;
volatile int PathSize = 0;
int dir = 5;
volatile int i=0;
Main MainPassed=new Main();
DijkstraSolve PathFinder = new DijkstraSolve();
Task<Void> task = new Task<Void>() {
@Override protected Void call() throws Exception {
while (Continue) {
i = 0;
width = MainPassed.width;
ChaserX = ((int) (PlayerIns.chaser.getCenterX() / width) * width);
ChaserY = ((int) (PlayerIns.chaser.getCenterY() / width) * width);
PlayerX = ((int) (PlayerIns.player.getCenterX() / width) * width);
PlayerY = ((int) (PlayerIns.player.getCenterY() / width) * width);
Path = PathFinder.Dijkstra(ChaserX, ChaserY, PlayerX, PlayerY, MainPassed);//wait for this to return??
PathSize = Path.size() - 1;
}
return null;
}
};
Thread th = new Thread(task);
//th.setDaemon(true);
th.start();
public void MoveChaser(Player PlayerIns){
Timeline timeline = new Timeline(new KeyFrame(Duration.millis(50), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println(" current path "+Path);
System.out.println("==============================");
}
}));
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
}
}
解决方案
您正忙于循环并可能使 UI 线程处于饥饿状态。您还没有展示如何声明变量。(而且您使用的非标准命名约定会导致混淆。请不要用大写字母命名变量,以免它们看起来像类。)
也许 Path 变量(应该命名为 'path')没有声明为 volatile?
推荐阅读
- c++ - Clang AST Matcher 和 AST Visitor 有什么区别?
- ruby-on-rails - 如何清理代码并消除 NoMethodError 异常
- c# - .NET 问题从单元测试中删除 TestContext
- c# - ASP.Net Core 3 MVC 中的多个绑定(前缀 =“...”)
- java - 如何根据客户端应用程序动态获取 EJB jar 中的数据源名称
- angular - 默认路由中带有占位符的角度路由
- java - 在测试用例中没有从 application.yml 文件中获取值?
- pandas - 使用 Altair 绘制多索引数据框
- python-3.x - 如何在从 python 调用时摆脱 VBS 命令外壳
- data-visualization - 在 Mapbox Studio 中排除指定区域之外的标签