ExecutorService中的不确定任务 [英] Indefinite task in ExecutorService
问题描述
我有以下变量:
private ExecutorService executor;
private Task<Boolean> worker;
我有一个任务应该在另一个线程中执行,并且应该监视其状态:
I have a task that should be performed in another thread and the state of which should be monitored:
public Worker<Boolean> updateTemplateBuffer() {
worker = new Task<Boolean>() {
@Override
protected Boolean call() throws Exception {
//task code
};
executor.execute(worker);
return worker;
}
任务已正确执行,但我无法跟踪任务是否结束.
The task is executed correctly, but I can’t track whether the task has ended or not.
方法executor.isTerminated()
和executor.isShutdown()
始终在调用时始终为false
.
告诉我如何正确跟踪任务的状态(开始或完成),因为我以前从未遇到过多线程编程.
Methods executor.isTerminated()
and executor.isShutdown()
always false
anytime of a call.
Tell me how to track the state of the task correctly (started or completed), because I had never encountered multi-threaded programming before.
推荐答案
state
属性.您可以在 SUCCEEDED
,CANCELLED
或FAILED
.
Task
implements the Worker
interface which has the state
property. You can listen to this property and react when the Worker.State
changes to SUCCEEDED
, CANCELLED
, or FAILED
.
Task<Boolean> task = ...;
task.stateProperty().addListener((obs, oldVal, newVal) -> {
// Test newVal and do something as needed...
});
或者您可以收听 running
属性.
Or you could listen to the running
property.
task.runningProperty().addListener((obs, oldVal, newVal) -> {
if (!newVal) {
// Do something...
}
});
您还可以收听 WorkerStateEvent
上的> s.
You can also listen for WorkerStateEvent
s on the Task
.
task.setOnSucceeded(event -> {});
task.setOnCancelled(event -> {});
task.setOnFailed(event -> {});
// or even something like
task.addEventHandler(WorkerStateEvent.ANY, event -> {
// Test event type and do something as needed...
});
然后还有受保护的状态方法".
Then there's also the protected "state methods".
Task<Boolean> task = new Task<>() {
@Override
protected Boolean call() throws Exception {
return false;
}
@Override protected void succeeded() {}
@Override protected void cancelled() {}
@Override protected void failed() {}
});
所有这些选项都会在 JavaFX Application Thread 上通知您.
All these options will notify you on the JavaFX Application Thread.
这篇关于ExecutorService中的不确定任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!