我想知道是否有一种方法可以将参数传递给从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()能够接受String参数,以便String变量ClusterID可以来自ProteinariumThread类之外?
final ProteinariumThread service = new ProteinariumThread();
service.start(ClusterID);
答案 0 :(得分:3)
您只需要为服务类提供一个接受必要参数的构造函数和/或方法即可。由于服务具有可重用性,因此最好通过公开属性来允许在服务的整个生命周期中进行配置:
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();
}