最简单的方法是使用
Task。
Platform.runLater仅当您需要从其他线程更新UI时才需要,因此在您的情况下则不需要。如果要在后台任务运行时跟踪其进度,可以在任务中使用
updateMessage和
updateProgress方法将消息安全地传递到UI线程,而不必担心通过EDT进行调度。您可以在这里https://docs.oracle.com/javase/8/javafx/interoperability-
tutorial/concurrency.htm上找到更多信息。
请参阅下面的最小工作示例。
import javafx.application.Application;import javafx.concurrent.Task;import javafx.scene.Scene;import javafx.scene.control.MenuButton;import javafx.scene.control.MenuItem;import javafx.scene.control.ToolBar;import javafx.stage.Stage;public class BlockingThreadTestCase extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { MenuItem menuItem = new MenuItem("Start"); MenuButton menuButton = new MenuButton(); menuButton.setText("Async Process"); menuButton.getItems().addAll(menuItem); menuItem.setonAction(event -> { menuButton.setText("Running..."); Task task = new Task<Void>() { @Override public Void call() { //SIMULATE A FILE DOWNLOAD try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } return null; } }; task.setonSucceeded(taskFinishEvent -> menuButton.setText(menuButton.getText() + "Done!")); new Thread(task).start(); }); final ToolBar toolbar = new ToolBar(menuButton); final Scene scene = new Scene(toolbar); primaryStage.setScene(scene); primaryStage.setWidth(150); primaryStage.show(); }}


