gpt4 book ai didi

java - 处理 SwingWorker.doInBackground 引发的异常的正确方法

转载 作者:行者123 更新时间:2023-12-01 22:07:19 25 4
gpt4 key购买 nike

处理 doInBackground 抛出的异常的正确方法方法SwingWorker类是调用 get done 中的方法方法,如所解释的herehere .

get 的文档方法说明如下:

Waits if necessary for the computation to complete, and then retrieves its result.

Note: calling get on the Event Dispatch Thread blocks all events, including repaints, from being processed until this SwingWorker is complete.

因此,如果 get 方法导致 done 方法内等待,实际上它会阻塞事件调度线程,因为 done > 方法在 EDT 上执行。

但是,在对建议的解决方案执行简单测试后,您可能会注意到 EDT 并未被阻止:出现此行为是因为在 done 中调用了 get 方法> 方法,因此 get 是在计算出运算结果之后调用的,因此对其的调用不会阻塞 EDT。这个动机正确吗?

最佳答案

Therefore, if the get method causes a waiting within the done method, in fact it would block the Event Dispatch Thread, since the done method is executed on EDT.

实际上,如果调用done,doInBackground已经返回,因此在done中调用get不会阻塞事件调度线程。

如果您使用 PropertyChangeListener 支持并监视 DONE 状态的更改,情况也是如此

已更新

所以,在查看 SwingWorker calls 'done' before the 'doInBackground' is finished 后,这意味着对已取消的工作线程调用 get 会无意中阻塞 EDT,基本的解决方法实际上是通过检查 SwingWorker#isCancelled 状态来忽略返回结果。让我们面对现实吧,如果工作线程被取消,返回结果是未知/未定义的,所以最好不要尝试获取它。

作为示例(基于 bug 中的代码)

import java.util.concurrent.ExecutionException;
import javax.swing.SwingWorker;

public class Main {

public static void main(String[] args) throws InterruptedException {
SwingWorker<String, String> worker = new SwingWorker<String, String>() {
@Override
protected String doInBackground() throws Exception {
try {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Working...");
Thread.sleep(1000);

}
} catch (InterruptedException ex) {
System.out.println("Got interrupted!");
}

try {
System.out.println("Cleaning up");
Thread.sleep(10000);
System.out.println("Done cleaning");
} catch (InterruptedException ex) {
System.out.println("Got interrupted second time!");
}

return null;
}

@Override
protected void done() {
System.out.println("Done");
if (!isCancelled()) {
long start = System.currentTimeMillis();
try {
get();
} catch (InterruptedException | ExecutionException ex) {
ex.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("Took " + ((end - start) / 1000d));
} else {
System.out.println("Was cancelled");
}
}
};

worker.execute();

Thread.sleep(10000);

worker.cancel(true);
Thread.sleep(20000);
}
}

关于java - 处理 SwingWorker.doInBackground 引发的异常的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32445902/

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