首页 > 解决方案 > 在再次循环之前等待循环内的方法完成

问题描述

我正在构建一个 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();
}

}

标签: javamultithreadingloopsrecursionjavafx

解决方案


您正忙于循环并可能使 UI 线程处于饥饿状态。您还没有展示如何声明变量。(而且您使用的非标准命名约定会导致混淆。请不要用大写字母命名变量,以免它们看起来像类。)

也许 Path 变量(应该命名为 'path')没有声明为 volatile?


推荐阅读