我一直试图让这个线程等待,但它不会等待或抛出异常或做任何事情......(我创建了一个新线程来运行线程,因为否则我的gui因为调用wait方法而冻结edt)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Sandbox extends JFrame {
boolean paused = false;
Thread thread = new Thread() {
public void run() {
while(true) {
System.out.println("running...");
}
}
};
private JButton button;
public Sandbox() throws Exception {
thread.start();
setSize(300, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(3);
add(button = new JButton("Pause"));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Thread() {
public void run() {
synchronized(thread) {
try {
if(button.getText().equals("Pause")) {
thread.wait();
button.setText("Resume");
} else if(button.getText().equals("Resume")) {
thread.notify();
button.setText("Pause");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}});
setVisible(true);
}
public static void main(String[] args) throws Exception {
new Sandbox();
}
}
答案 0 :(得分:1)
如果您要比较字符串,则需要使用equals()
而不是==
if(button.getText().equals("Pause")) {
thread.wait();
button.setText("Resume");
} else if(button.getText().equals("Resume")) {
thread.notify();
button.setText("Pause");
}
但是使用wait和notify可能不会真正做你想要的。