等待取消的未来实际完成 [英] Waiting for a cancelled future to actually finish

查看:94
本文介绍了等待取消的未来实际完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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) {

        }
    }

}

这篇关于等待取消的未来实际完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆