Make a JavaFX application thread wait for another thread to finish

I am calling a method inside my user interface thread. A new thread is created inside this method. I need a user interface thread to wait until this new thread is completed, because I need the results of this thread to continue the method in the user interface thread. But I do not want the user interface to be frozen while waiting. Is there a way to make the user interface queue wait without waiting?

+1
source share
2 answers

You should never wait for a stream of FX applications; it will freeze the user interface and make it unresponsive, both in terms of processing user actions and in terms of displaying something on the screen.

If you want to update the user interface at the end of a lengthy process, use the javafx.concurrent.TaskAPI . For example.

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 SomeKindOfResultwith what type of data represents the result of your long process.

Please note that the code in the block onSucceeded:

  • must be performed after task completion
  • has access to the result of the background task through task.getValue()
  • essentially it is in the same volume as the place where you started the task, so it has access to all elements of the user interface, etc.

, , , " ", .

+8

, GUI Thread. - :

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

Source: https://habr.com/ru/post/1628555/


All Articles