Pau*_*ing 6 java future swingworker
我有一个SwingWorker调用一些不检查线程中断的代码.调用之后worker.cancel(true),该worker.get()方法将CancellationException立即抛出(正如它应该的那样).但是,由于后台任务的代码从不检查其线程是否被中断,因此它很乐意继续执行.
是否存在等待后台任务实际完成的标准方法?我希望显示一个"正在取消..."消息或类似的东西,并阻止任务终止.(我确信如果有必要,我可以在工人类中使用标志来完成此操作,只需查找其他任何解决方案.)
我对此进行了一些尝试,这就是我的想法。我正在使用 a 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) {
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2378 次 |
| 最近记录: |