Java:线程不会等待
问题描述:
我一直试图让这个线程等待,但它没有等待或抛出异常或做任何事情......(我创建了一个新线程来运行线程,否则我的GUI会冻结,因为呼吁美国东部时间wait方法)Java:线程不会等待
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();
}
}
答
如果你是比较你需要使用equals()
字符串,而不是==
if(button.getText().equals("Pause")) {
thread.wait();
button.setText("Resume");
} else if(button.getText().equals("Resume")) {
thread.notify();
button.setText("Pause");
}
但使用等待和通知可能不会真的做你想做的。
+0
是的,我明白,这只是粗略的代码,以解决问题一直处理了相当长的一段时间。那么我还能用什么? –
你不应该在'Thread'对象上调用'wait'。使用'join'等待它完成。 'wait/notify'用于具有条件变量行为。 – zch
我不认为这个线程将永远不会死......虽然它在一个while循环中无限期地延续 –
我认为你不明白“wait”方法的作用。当你调用'thread.wait()'时,你希望发生什么? – zch