更新任务中的消息挂起应用程序

Updating message in task hangs the application

我正在使用背景 Thread 到 运行 我的加载代码,并希望将 TaskMessageProperty 绑定到标签。

但是,当调用 updateMessage() 时任务挂起;消息永远不会更新,下一行代码也不会执行。

这是使用 JDK 1.10.1。这是一个 MCVE:

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        VBox root = new VBox(10);
        Label label = new Label("Message");
        root.getChildren().add(label);

        primaryStage.setScene(new Scene(root));

        Task loadingTask = new LoadingTask();
        Thread loadingThread = new Thread(loadingTask);
        loadingThread.setDaemon(true);

        label.textProperty().bind(loadingTask.messageProperty());
        loadingThread.start();

        primaryStage.setWidth(200);
        primaryStage.setHeight(200);
        primaryStage.show();
    }
}

class LoadingTask<Void> extends Task {
    @Override
    protected Object call() throws Exception {
        System.out.println("Loading task ...");
        updateMessage("Loading task ...");
        System.out.println("Message: " + getMessage());

        return null;
    }
}

输出:

Loading task ...

第二个 System.out.println() 永远不会执行。

编辑:

我在我的 MCVE 中添加了一个简单的 GUI,并带有绑定到 MessageProperty 的标签。标签 does 更新为显示 "Loading task ..." 但控制台输出保持不变; updateMessage()方法调用后的代码不执行。

第二次编辑:

我 运行 我的步骤调试器,IllegalStateExceptionTask class 抛出:"Task must only be used from the FX Application Thread"

我不确定这意味着什么,因为重点是 运行 这个任务在不同的线程上...

您唯一的问题是,您不能从除 FX UI-Thread 之外的其他线程访问 getMessage()。尝试 Platform.runLater(() -> System.out.println("Message: " + getMessage()));