我有以下JavaFX部分实现Service
类:
public void processingImage() {
Task<Void> track = new Task<Void>() {
@Override
protected Void call() throws Exception {
while (true) {
if (flag == false) {
if (someCondition) {
flag = true;
CommunicateServer.sendObject = new Object[2];
CommunicateServer.sendObject[0] = 6;
CommunicateServer.sendObject[1] = "hello";
myService.start();
flag = false;
System.out.println("this line does not print");
}
}
return null;
}
};
Thread th1 = new Thread(track);
th1.setDaemon(true);
th1.start();
}
MyService
类实现为:
private class MyService extends Service<Void> {
@Override
protected Task<Void> createTask() {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
CommunicateServer.callSendObject(CommunicateServer.sendObject, true);
response = CommunicateServer.getObject();
System.out.println("this print should have been many times but only executed once!!!!");
return null;
}
};
}
}
我的问题是虽然我希望代码打印this line does not print
,但代码实际上并不打印这个。此外,行this print should have been many times but only executed once!!!!
只打印一次,虽然我认为应该多次打印。我不知道如何解决这个问题。任何帮助或建议都会得到感谢。
答案 0 :(得分:1)
您对代码的期望并不是很清楚,但Service.start()
should be called from the FX Application Thread。由于您是从后台线程调用它,因此可能会抛出异常,导致您无法访问System.out.println(...)
语句。
此外,服务必须处于READY
状态才能接收对start()
的调用,因此在第二次执行时(如果有),由于服务尚未重置,您将获取IllegalArgumentException
,退出call()
中定义的任务中的processingImage()
方法。因此,您的服务最多只能执行一次。