首页 > 解决方案 > 将参数传递给扩展服务类 Java 的类

问题描述

我想知道是否有一种方法可以将参数传递给从 Javafx 并发包中扩展 Service 类的类。我希望 ProteinariumThread 接受如下所示的 ClusterID 之类的字符串参数:

public class ProteinariumThread extends Service<String>{
    String ClusterID = "q";
    @Override


    protected Task<String> createTask(){

        return new Task<String>() {
            @Override
            protected String call() throws Exception {
                updateMessage("Running Proteinarium");
                System.out.println("Asleep");
                ProteinariumRun.PRun(ClusterID);
                System.out.println("Woke Up");
                String woke = "Woke Up";
                return woke;
            }
        };
    }
}

目前为了运行这个后台任务,我使用以下代码:

final ProteinariumThread service = new ProteinariumThread();
service.start();

但是,这不允许我接受 String 参数。有没有办法让 service.start() 能够接受字符串参数,以便字符串变量 ClusterID 可以来自 ProteinariumThread 类的外部?

final ProteinariumThread service = new ProteinariumThread();
service.start(ClusterID);

标签: javafxserviceconcurrency

解决方案


您只需要为您的服务类提供一个接受必要参数的构造函数和/或方法。由于服务是可重用的,因此最好通过公开属性来允许在服务的整个生命周期中进行配置:

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.concurrent.Service;
import javafx.concurrent.Task;

public class ProteinariumService extends Service<String> {

  private final StringProperty clusterId = new SimpleStringProperty(this, "clusterId");
  public final void setClusterId(String clusterId) { this.clusterId.set(clusterId); }
  public final String getClusterId() { return clusterId.get(); }
  public final StringProperty clusterIdProperty() { return clusterId; }

  public ProteinariumService() {}

  public ProteinariumService(String clusterId) {
    setClusterId(clusterId);
  }

  @Override
  protected Task<String> createTask() {
    return new Task<>() {

        final String clusterId = getClusterId(); // cache configuration

        @Override
        protected String call() throws Exception {
            ...
        }
    };
  }
}

将所需状态从服务复制到任务很重要,因为任务是在后台线程上执行的。

然后,当您需要更改集群 ID 时,您只需执行以下操作:

// or bind the property to something in the UI (e.g. a TextField)
theService.setClusterId(newClusterId);
theService.start();

如果你真的希望能够在一行中做到这一点,你总是可以start在你的服务类中定义一个重载:

public void start(String clusterId) {
  setClusterId(clusterId):
  start();
}

推荐阅读