再次循环之前等待循环内的方法完成

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

}

}



婷婷同学_
浏览 105回答 2
2回答

暮色呼如

您正忙于循环并可能导致 UI 线程饥饿。您还没有显示变量是如何声明的。(并且您使用的非标准命名约定会导致混乱。请不要用大写字母命名变量,这样它们看起来就像类。)也许 Path 变量(应该命名为“path”)没有声明为 volatile?

MMTTMM

您可以通过使用以下join()方法来实现此目的,当从父线程调用此方法时,父线程将等待直到子线程终止。th.join()之后使用th.start()。您的任务应该在执行这两个命令之间运行。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java