一个服务可以启动多个任务吗?
Can a Service starts several Tasks?
我需要使用 Service
多次启动 Task
(= 相同的 Service
必须 运行 多个并行化 Task
)。我阅读了 JavaFX 文档,他们似乎说 Service
一次只能 运行 一个 Task
。
所以如果我用我的 Service
对象调用两次 start
,它的 createTask
方法返回的第一个 Task
将被停止,就好像我使用 restart
在第一个 start
.
之后
然而,这还不清楚。正如我告诉您的,文档 似乎 说明了这一点。
确实 :
A Service creates and manages a Task that performs the work on the background thread.
请注意,我认为他们还说 Service
可以同时启动多个 Task
。确实 :
a Service can be constructed declaratively and restarted on demand.
我的问题是:如果我连续使用 N start
,是否会创建 N Tasks
并保留每个 运行?
"If I use N start in a row, will N Tasks be created AND KEEP EACH RUNNING ?
简而言之,没有。
"If I call start
twice with my Service
object..."
来自Javadocs:
public void start()
Starts this Service. The Service must be in the READY state to succeed in this call.
因此,如果您在之前未调用 reset()
的情况下再次调用 start()
,您只会得到一个异常。如果 Service
不处于 RUNNING
或 SCHEDULED
状态,则只能调用 reset()
。您可以调用 restart()
,这将产生 首先取消任何当前任务 ,然后重新启动服务的效果。 (这就是说“服务可以按需重启”的文档的意思。)
最终结果是一个服务不能同时有两个当前 运行ning 任务,因为没有调用序列可以在不抛出 IllegalStateException
.
如果您想要同时执行多个任务 运行,只需自己创建它们并将它们提交给执行程序(或者 运行 每个任务都在自己的线程中,但最好使用执行程序):
private final Executor exec = Executors.newCachedThreadPool(runnable -> {
Thread t = new Thread(runnable);
t.setDaemon(true);
return t ;
});
// ...
private void launchTask() {
Task<MyDataType> task = new Task<MyDataType>(){
@Override
protected Something call() {
// do work...
return new MyDataType(...);
}
};
task.setOnSucceeded(e -> { /* update UI ... */ });
task.setOnFailed(e -> { /* handle error ... */ });
exec.execute(task);
}
我需要使用 Service
多次启动 Task
(= 相同的 Service
必须 运行 多个并行化 Task
)。我阅读了 JavaFX 文档,他们似乎说 Service
一次只能 运行 一个 Task
。
所以如果我用我的 Service
对象调用两次 start
,它的 createTask
方法返回的第一个 Task
将被停止,就好像我使用 restart
在第一个 start
.
然而,这还不清楚。正如我告诉您的,文档 似乎 说明了这一点。 确实 :
A Service creates and manages a Task that performs the work on the background thread.
请注意,我认为他们还说 Service
可以同时启动多个 Task
。确实 :
a Service can be constructed declaratively and restarted on demand.
我的问题是:如果我连续使用 N start
,是否会创建 N Tasks
并保留每个 运行?
"If I use N start in a row, will N Tasks be created AND KEEP EACH RUNNING ?
简而言之,没有。
"If I call
start
twice with myService
object..."
来自Javadocs:
public void start()
Starts this Service. The Service must be in the READY state to succeed in this call.
因此,如果您在之前未调用 reset()
的情况下再次调用 start()
,您只会得到一个异常。如果 Service
不处于 RUNNING
或 SCHEDULED
状态,则只能调用 reset()
。您可以调用 restart()
,这将产生 首先取消任何当前任务 ,然后重新启动服务的效果。 (这就是说“服务可以按需重启”的文档的意思。)
最终结果是一个服务不能同时有两个当前 运行ning 任务,因为没有调用序列可以在不抛出 IllegalStateException
.
如果您想要同时执行多个任务 运行,只需自己创建它们并将它们提交给执行程序(或者 运行 每个任务都在自己的线程中,但最好使用执行程序):
private final Executor exec = Executors.newCachedThreadPool(runnable -> {
Thread t = new Thread(runnable);
t.setDaemon(true);
return t ;
});
// ...
private void launchTask() {
Task<MyDataType> task = new Task<MyDataType>(){
@Override
protected Something call() {
// do work...
return new MyDataType(...);
}
};
task.setOnSucceeded(e -> { /* update UI ... */ });
task.setOnFailed(e -> { /* handle error ... */ });
exec.execute(task);
}