Make JavaFX application thread wait for another Th

2020-03-26 08:19发布

问题:

I am calling a method inside my UI thread. Inside this method a new thread is created. I need the UI thread to wait until this new thread is finished because I need the results of this thread to continue the method in the UI thread. But I don´t want to have UI frozen while its waiting. Is there some way to make the UI thread wait without busy waiting?.

回答1:

You should never make the FX Application Thread wait; it will freeze the UI and make it unresponsive, both in terms of processing user action and in terms of rendering anything to the screen.

If you are looking to update the UI when the long running process has completed, use the javafx.concurrent.Task API. E.g.

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();
});

Obviously replace SomeKindOfResult with whatever data type represents the result of your long-running process.

Note that the code in the onSucceeded block:

  1. is necessarily executed once the task has finished
  2. has access to the result of the execution of the background task, via task.getValue()
  3. is essentially in the same scope as the place where you launched the task, so it has access to all the UI elements, etc.

Hence this solution can do anything you could do by "waiting for the task to finish", but doesn't block the UI thread in the meantime.



回答2:

Just call a method that notifies the GUI when the Thread is finished. Something like this:

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();
      }
   }
}