好的,所以我一直在使用 SwingWorker 并获得了一些用于更新 gui 的简化代码,但我无法弄清楚如何让线程在完成时正确终止。目前,它仅通过停止选项终止。我将如何设置它以在完成其进程时也正确终止线程?目前,在return null;
它进入包装线并挂起之后。
我的代码如下:
package concurrency;
import java.util.List;
import java.util.Random;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class PBTest extends JFrame implements ActionListener {
private final GridBagConstraints constraints;
private final JProgressBar pb, pbF;
private final JButton theButton;
private PBTask pbTask;
private JProgressBar makePB() {
JProgressBar p = new JProgressBar(0,100);
p.setValue(0);
p.setStringPainted(true);
getContentPane().add(p, constraints);
return p;
}
public PBTest() {
super("PBTest");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Make text boxes
getContentPane().setLayout(new GridBagLayout());
constraints = new GridBagConstraints();
constraints.insets = new Insets(3, 10, 3, 10);
pb = makePB();
pbF = makePB();
//Make buttons
theButton = new JButton("Start");
theButton.setActionCommand("Start");
theButton.addActionListener(this);
getContentPane().add(theButton, constraints);
//Display the window.
pack();
setVisible(true);
}
private static class UpdatePB {
private final int pb1, pb2;
UpdatePB(int pb1s, int pb2s) {
this.pb1 = pb1s;
this.pb2 = pb2s;
}
}
private class PBTask extends SwingWorker<Void, UpdatePB> {
@Override
protected Void doInBackground() {
int prog1 = 0;
int prog2 = 0;
Random random = new Random();
while (prog2 < 100) {
if(prog1 >= 100) {
prog1 = 0;
}
//Sleep for up to one second.
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException ignore) {}
//Make random progress.
prog1 += random.nextInt(10);
prog2 += random.nextInt(5);
publish(new UpdatePB(prog1, prog2));
}
return null;
}
@Override
protected void process(List<UpdatePB> pairs) {
UpdatePB pair = pairs.get(pairs.size() - 1);
pb.setValue(pair.pb1);
pbF.setValue(pair.pb2);
}
}
public void actionPerformed(ActionEvent e) {
if ("Start" == e.getActionCommand() && pbTask == null) {
theButton.setText("Stop");
theButton.setActionCommand("Stop");
(pbTask = new PBTask()).execute();
} else if ("Stop" == e.getActionCommand()) {
theButton.setText("Start");
theButton.setActionCommand("Start");
pbTask.cancel(true);
pbTask = null;
} else {
alertMsg("Thread still running.");
}
}
static void alertMsg(String theAlert) {
JOptionPane.showMessageDialog(null, theAlert);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new PBTest();
}
});
}
}
注意:这基本上是对 Java 教程的“flipper”示例的修改......我现在不是程序员而是代码黑客(/sad face/,lol),所以我有点不知道下一步该去哪里。
无论如何,代码按预期工作,直到完成。我尝试添加该done()
方法,但它从不尝试运行它,它总是只是转到包行(当单步调试器时)并挂起。我应该返回 null 以外的值吗?
提前感谢您的帮助!