Ian*_*Ian 6 java swing multithreading swingworker
我正在尝试使用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();
}
});
Run Code Online (Sandbox Code Playgroud)
我可以随意点击按钮多次,Gui将保持响应,直到两个线程完成,此时Gui在线程运行时冻结.如果我一次只运行一个线程,则仍会出现此问题.
如果有人能指出我是否错误地使用了SwingWorker,或者是否有其他我不知道的问题,我会很高兴.谢谢你的时间.伊恩
编辑
doCalculation()只是耗费时间:
private String doCalculation() {
for (int i = 0; i < 10000000; i++) {
Math.pow(3.14, i);
}
return threads++ + "";
}
Run Code Online (Sandbox Code Playgroud)
对不起,但即使你的doCalculate()方法,我仍然无法重现你的问题.例如,这是我的sscce:
import java.awt.event.*;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
public class FooGui {
private static int threads = 0;
private static void createAndShowUI() {
final JLabel label = new JLabel(" ");
JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
new SwingWorker<String, Void>() {
@Override
protected String doInBackground() throws Exception {
return doCalculation();
}
@Override
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();
}
});
JPanel panel = new JPanel();
panel.add(button);
panel.add(label);
JFrame frame = new JFrame("FooGui");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static String doCalculation() {
for (int i = 0; i < 5000000; i++) {
Math.pow(3.14, i);
}
return threads++ + "";
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowUI();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
您可能希望创建并发布自己的"简短,自包含,正确(可编译),示例"或SSCCE(请查看链接).我敢打赌,在创建这个过程中,您可能会自己找到问题及其解决方案.如果是这样,请务必回到这里告诉我们.
我知道这不是一个真正的答案,但是没有办法在评论中发布这样的代码.