0

I'm trying to build an application that will execute several queries in a loop. Queries are to be executed one by one (one after the other). If I do code in one thread, the GUI freezes for the duration of the queries (they take a while) and only after they are finished is it active again, and I would like to have a working progress bar as well.

protected void onButtonClick() throws InterruptedException {
    String[] array = getIDs();

    progressText.setText("Starting...");
    for (int i = 0; i < array.length; i++) {
        progressText.setText("Updated: " + i + " of " + array.length + " ids.");

        executeSingleQuery(array[i]);
    }
    progressText.setText("Done!");
}

I know I should work on threads probably, but I don't really know how. If I add

new Thread(() ->executeSingleQuery(array[i])).start();

to the loop, a new thread will be created with each iteration, and my point is that the queries should be executed one at a time; plus I want the progress bar to work properly. Can you help me find a solution?

Mio
  • 175
  • 2
  • 11
  • 1
    Use a `javafx.concurrent.Task` (and use its API for messages/progress). See [Concurrency in JavaFX](https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm#JFXIP546). – Slaw Oct 22 '21 at 08:50
  • Alternatively you can execute the entire for loop on a separate thread. When you update the GUI do it using the JavaFx thread by `Platform.runLater(()-> progressText.setText("Starting..."));` – c0der Oct 22 '21 at 08:59

0 Answers0