我有一个SwingWorker
它调用一些不检查线程中断的代码。拨打电话后worker.cancel(true)
, the worker.get()
方法会抛出CancellationException
立即(正如预期的那样)。但是,由于后台任务的代码从不检查其线程是否被中断,因此它会愉快地继续执行。
是否有等待后台任务的标准方法actually结束?我希望显示“正在取消...”消息或类似的消息并阻止,直到任务终止。 (我确信如果有必要,我总是可以在工人类中使用标志来完成此任务,只需寻找任何其他解决方案。)
我对此进行了一些尝试,这就是我的想法。我正在使用一个CountDownLatch
并基本上暴露了它的await()
方法作为我的方法SwingWorker
目的。仍在寻找更好的解决方案。
final class Worker extends SwingWorker<Void, Void> {
private final CountDownLatch actuallyFinishedLatch = new CountDownLatch(1);
@Override
protected Void doInBackground() throws Exception {
try {
System.out.println("Long Task Started");
/* Simulate long running method */
for (int i = 0; i < 1000000000; i++) {
double d = Math.sqrt(i);
}
return null;
} finally {
actuallyFinishedLatch.countDown();
}
}
public void awaitActualCompletion() throws InterruptedException {
actuallyFinishedLatch.await();
}
public static void main(String[] args) {
Worker worker = new Worker();
worker.execute();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
System.out.println("Cancelling");
worker.cancel(true);
try {
worker.get();
} catch (CancellationException e) {
System.out.println("CancellationException properly thrown");
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
System.out.println("Awaiting Actual Completion");
try {
worker.awaitActualCompletion();
System.out.println("Done");
} catch (InterruptedException e) {
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)