使JavaFX应用程序线程等待另一个Thread完成

Jup*_*ter 2 java multithreading javafx

我在UI线程中调用一个方法.在此方法中,将创建一个新线程.我需要UI线程等到这个新线程完成,因为我需要这个线程的结果来继续UI线程中的方法.但我不想在等待时冻结UI.有没有办法让UI线程在没有忙等待的情况下等待?

Jam*_*s_D 8

你永远不应该让FX应用程序线程等待; 它会冻结UI并使其无响应,无论是在处理用户操作方面还是在向屏幕呈现任何内容方面.

如果您希望在长时间运行的进程完成后更新UI,请使用javafx.concurrent.TaskAPI.例如

someButton.setOnAction( event -> {

    Task<SomeKindOfResult> task = new Task<SomeKindOfResult>() {
        @Override
        public SomeKindOfResult call() {
            // process long-running computation, data retrieval, etc...

            SomeKindOfResult result = ... ; // result of computation
            return result ;
        }
    };

    task.setOnSucceeded(e -> {
        SomeKindOfResult result = task.getValue();
        // update UI with result
    });

    new Thread(task).start();
});
Run Code Online (Sandbox Code Playgroud)

显然,SomeKindOfResult用任何数据类型替换代表长时间运行进程的结果.

请注意onSucceeded块中的代码:

  1. 必须在任务完成后执行
  2. 可以通过访问后台任务的执行结果 task.getValue()
  3. 基本上与您启动任务的地方的范围相同,因此它可以访问所有UI元素等.

因此,此解决方案可以通过"等待任务完成"来执行任何操作,但在此期间不会阻止UI线程.


Kev*_*man 1

只需调用一个方法,在线程完成时通知 GUI。像这样的东西:

class GUI{

   public void buttonPressed(){
      new MyThread().start();
   }

   public void notifyGui(){
      //thread has finished!

      //update the GUI on the Application Thread
      Platform.runLater(updateGuiRunnable)
   }

   class MyThread extends Thread{
      public void run(){
         //long-running task

         notifyGui();
      }
   }
}
Run Code Online (Sandbox Code Playgroud)