我有 2 个按钮。第一个启动线程,第二个让它等待。第一个按钮工作正常,但第二个不想停止第一个按钮线程。怎么了?如何让它停止?
package SwingExp;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WhichButton implements ActionListener {
JLabel jLab, testLab = new JLabel();
JFrame jfrm = new JFrame("Button example");
JButton firstButton = new JButton("First"), secondButton = new JButton("Second");
WhichButton() {
jfrm.setLayout(new FlowLayout());
jfrm.setSize(220, 90);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstButton.addActionListener(this);
secondButton.addActionListener(this);
jfrm.add(firstButton);
jfrm.add(secondButton);
jLab = new JLabel("Press button");
jfrm.add(jLab);
jfrm.add(testLab);
jfrm.setVisible(true);
}
class SimpleThread extends Thread {
Thread t;
boolean suspendFlag;
SimpleThread() {
t = new Thread(this, "settingThread");
t.start();
}
public void run() {
for (int i = 0; i <= 10; i++) {
synchronized (this) {
while (suspendFlag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
testLab.setText(Integer.toString(i));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
firstButton.setEnabled(true);
testLab.setText("Completed.");
}
synchronized void setSuspendFlag(boolean suspendFlag) {
this.suspendFlag = suspendFlag;
}
}
public void actionPerformed(ActionEvent e) {
SimpleThread st = new SimpleThread();
if (e.getActionCommand().equals("First")) {
jLab.setText("First");
firstButton.setEnabled(false);
st.setSuspendFlag(false);
} else {
st.setSuspendFlag(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new WhichButton();
}
});
}
}
我试图使用interrupt()
方法,但它让我多了一个线程或类似的东西。