开发者

How to abort a already-started swing worker thread?

开发者 https://www.devze.com 2023-01-17 15:35 出处:网络
If I have started a SwingWorker thread by invoking its ex开发者_如何学Cecute(). Is there any way that I can interrupt it at its execution? If you control the code of the SwingWorker, you can poll isCa

If I have started a SwingWorker thread by invoking its ex开发者_如何学Cecute(). Is there any way that I can interrupt it at its execution?


If you control the code of the SwingWorker, you can poll isCancelled() at appropriate places in doInBackground(), and then stop doing work if it returns true. Then cancel the worker when you feel like it:

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

Now, as you noted, cancel(boolean) can fail, but why? The Javadocs inform us:

Returns:

false if the task could not be cancelled, typically because it has already completed normally; true otherwise.

0

精彩评论

暂无评论...
验证码 换一张
取 消