gpt4 book ai didi

java - 如何中止已经启动的 Swing 工作线程?

转载 作者:行者123 更新时间:2023-11-30 05:58:55 25 4
gpt4 key购买 nike

如果我通过调用它的execute() 启动了一个SwingWorker 线程。有什么办法可以在执行时中断它吗?

最佳答案

如果你控制了S​​wingWorker的代码,你可以轮询isCancelled()doInBackground()中的适当位置,然后如果返回 true 则停止工作。然后cancel当你愿意时, worker :

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

现在,正如您所指出的,cancel(boolean) 可能会失败,但为什么呢? Javadocs通知我们:

Returns:

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

关于java - 如何中止已经启动的 Swing 工作线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3784953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com