收听来自 UI JavaFX 的后台线程

Listen to background thread from UI JavaFX

我有一个问题。我正在为桌面创建 JavaFX 应用程序。我的应用程序中有线程在后台运行,我们假设它正在从 Internet 下载文件。
我已阅读有关 JavaFX 中并发性的文章。有特殊的 class 任务。我用 Task 扩展了我的 class。但它只能 return 一些值,然后它会关闭。
但是我需要在整个应用程序生命周期内执行此任务 运行,并且当下载例如文件时,它应该 post 结果到 UI 线程,更精确的控制器依次更新一些 ui 组件。
我知道 Task 有 updateProgress 方法,也许我不仅可以绑定它来接收整数,还可以绑定复杂的对象。
或者在我的案例中还有其他好的方法可以遵循。
请帮助解决这个问题。

这里最简单的方法是使用普通的旧线程:

// create new thread at start, e.g. at the end for Application.start() method
new Thread(new Runnable() {
  public void run() {
      while(true) {
           //load my data 
           // once loaded
           // update UI using 
           Platform.runLater(new Runnable() {
               public void run() {
                   // here goes my update on FX UI thread
               }
           });
           // update is done let's look for more data
      }
  }
}).start();

JavaFX 为您提供ScheduledService 可以安排重复性工作。 javadoc 说,

The ScheduledService is a Service which will automatically restart itself after a successful execution, and under some conditions will restart even in case of failure.

一个非常简单的例子是:

ScheduledService<Object> service = new ScheduledService<Object>() {
     protected Task<Object> createTask() {
         return new Task<Object>() {
             protected Object call() {
                 // Connect to a Server
                 // Download the object
                 updateProgress(...);
                 return object; // Useful in case you want to return data, else null
             }
         };
     }
 };
 service.setPeriod(Duration.seconds(10)); //Runs every 10 seconds
 //bind the service progress/message properties
 progressBar.progressProperty().bind(service.progressProperty());

也有非 javafx 方法可以实现此目的,您可以使用: