【发布时间】:2011-10-16 13:36:00
【问题描述】:
我正在尝试使用 SwingWorker 执行冗长的任务并使用结果更新 JLabel:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
new SwingWorker<String, Void>() {
@Override
protected String doInBackground() throws Exception {
return doCalculation();
}
protected void done() {
try {
label.setText(get());
} catch (InterruptedException e) {
System.out.println("thread was interrupted");
} catch (ExecutionException e) {
System.out.println("there was an ExecutionException");
}
}
}.execute();
}
});
我可以根据需要多次单击该按钮,并且 Gui 将保持响应,直到两个线程完成,此时 Gui 在线程运行时冻结。如果我一次只运行一个线程,仍然会出现这个问题。
如果有人能指出我是否错误地使用了 SwingWorker 或者是否还有其他我不知道的问题,我将不胜感激。谢谢你的时间。 伊恩
编辑
doCalculation() 只是一些耗时的事情:
private String doCalculation() {
for (int i = 0; i < 10000000; i++) {
Math.pow(3.14, i);
}
return threads++ + "";
}
【问题讨论】:
-
到目前为止,我没有看到您发布的代码有任何明显错误,但我认为这里的关键是
doCalculation();方法中发生的事情。你能把这段代码贴出来吗?
标签: java multithreading swing swingworker