如何中止已经开始的摇摆工作线程?

dol*_*eng 2 java swing

如果我通过调用其execute()启动了SwingWorker线程.有什么方法可以在执行时打断它吗?

gus*_*afc 6

如果您控制SwingWorker的代码,则可以isCancelled()在适当的位置进行轮询doInBackground(),然后在返回时停止工作true.然后在你想要的时候取消工人:

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
Run Code Online (Sandbox Code Playgroud)

现在,正如你所说,cancel(boolean)可能会失败,但为什么呢?该Javadoc中告诉我们:

返回:

false如果任务无法取消,通常是因为它已经正常完成; true除此以外.