JavaFX thread blocking problem

foreword

During the development process, when executing the FTP file upload operation in the JavaFX Controller, the JavaFX thread is blocked and the modification to the JavaFX interface is not executed. I tried to use java.util.concurrent.FutureTask to execute the upload function, but it still failed.
After investigation, I learned that JavaFX itself provides the javafx.concurrent package to deal with multi-threaded code that interacts with the UI, ensuring that the interaction only occurs in the correct thread.

The Java platform provides a complete synchronization library in the java.util.concerrent package. The Javafx.concerrrent package balances the existing APIs by taking into account the constraints faced by JavaFX application threads and GUI developers.

javafx.concurrent.Task

To sum up, we can use javafx.concurrent.Task to perfectly solve the problem of thread blocking. The javafx.concurrent.Task class inherits the java.utils.concurrent.FutureTask class, so the usage is similar to FutureTask.

import javafx.concurrent.Task;

Task<Void> task = new Task<Void>() {
    @Override public Void call() {
        // 线程执行内容
        ...
        Platform.runLater(() -> {
            // 如果在线程执行中依然要对GUI进行修改,则调用
            ...
        });
        return null;
    }
};
new Thread(task).start();

refer to

  1. Concurrency in JavaFX / Translation

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325794476&siteId=291194637