如果您控制SwingWorker的代码,则可以isCancelled()在适当的位置进行轮询doInBackground(),然后在返回时停止工作true.然后在你想要的时候取消工人:
class YourWorker extends SwingWorker<Foo, Bar> {
// ...
protected Foo doInBackground() throws Exception {
while (someCondition) {
publish(doSomeIntermediateWork());
if (isCancelled())
return null; // we're cancelled, abort work
}
return calculateFinalResult();
}
}
// To abort the task:
YourWorker worker = new YourWorker(args);
worker.execute();
doSomeOtherStuff();
if (weWantToCancel)
worker.cancel(false); // or true, doesn't matter to us here
Run Code Online (Sandbox Code Playgroud)
现在,正如你所说,cancel(boolean)可能会失败,但为什么呢?该Javadoc中告诉我们:
返回:
false如果任务无法取消,通常是因为它已经正常完成;true除此以外.