Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make JavaFX application thread wait for another Thread to finish

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?.

like image 320
Jupiter Avatar asked Dec 10 '22 23:12

Jupiter


1 Answers

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.

like image 100
James_D Avatar answered Dec 28 '22 07:12

James_D