等待取消的未来实际完成

编程入门 行业动态 更新时间:2024-10-22 21:39:19
本文介绍了等待取消的未来实际完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 SwingWorker ,它会调用一些不检查线程中断的代码。在调用 worker.cancel(true)之后, worker.get()方法将抛出 CancellationException 立即(因为它应该)。但是,由于后台任务的代码永远不会检查其线程是否被中断,所以它很乐意继续执行。

I have a SwingWorker which calls some code that does not check for thread interruption. After the call to worker.cancel(true), the worker.get() method will throw CancellationException immediately (as it is supposed to). However, since the background task's code never checks for its thread to be interrupted, it happily continues executing.

是否存在等待后台任务到实际上完成了吗?我希望显示一个正在取消......消息或类似的东西,直到任务终止。 (我确信如果有必要,我可以在工人类中使用标志来完成此任务,只需查找其他任何解决方案。)

Is there a standard way to wait for the background task to actually finish? I'm looking to show a "Cancelling..." message or something of the sort and block until the task has terminated. (I'm sure I could always accomplish this with a flag in the worker class if necessary, just looking for any other solutions.)

推荐答案

我玩了一下这个,这就是我想出来的。我正在使用 CountDownLatch 并基本上将其 await()方法作为我的 SwingWorker 对象。仍在寻找任何更好的解决方案。

I played around with this a bit and here's what I came up with. I'm using a CountDownLatch and basically exposing its await() method as a method on my SwingWorker object. Still looking for any better solutions.

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) { } } }

更多推荐

等待取消的未来实际完成

本文发布于:2023-11-25 02:47:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628018.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:未来

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!