我有两个空的while循环等待用户在两个按钮上执行操作。一旦按下按钮,用于while条件的布尔值被设置为true,程序继续。Java:未在空while循环中检查条件?
代码是这样的:
public class test {
static JButton send = new JButton("Send");
static JButton yes = new JButton("Yes");
static boolean isSendButtonPressed = false;
static boolean isYesButtonPressed = false;
//...
public static void main(String[] args) {
send.addActionListener(new sendListener());
yes.addActionListener(new yesListener());
//...
while (!isSendButtonPressed) {} //works
System.out.println("Send button pressed");
while (!isYesButtonPressed) {} //doesn't work
System.out.println("Yes button pressed");
}
class sendListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
test.isSendButtonPressed = true;
}
}
class yesListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
test.isYesButtonPressed = true;
}
}
所以,当我按下“发送”按钮,isSendButtonPressed
设置为true,和它打印的声明。但是,除非我在while循环中放置指令(例如System.out.println),否则它不会为“是”按钮执行此操作。我真的不明白为什么第一次工作,但不是第二次,或者为什么它需要一个无用的指令工作。
这是一个**可怕的**方式等待输入... – Idos
请不要忙碌循环。即使你让这些布尔变量不稳定,这也是一个非常糟糕的主意。只需在互斥体上使用'Object.wait()',并让按钮处理程序通知该互斥体。 –
你应该使isYesButtonPressed(和isSendButtonPressed)'volatile' – ControlAltDel