2016-06-21 67 views
-1

我有两个空的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),否则它不会为“是”按钮执行此操作。我真的不明白为什么第一次工作,但不是第二次,或者为什么它需要一个无用的指令工作。

+2

这是一个**可怕的**方式等待输入... – Idos

+1

请不要忙碌循环。即使你让这些布尔变量不稳定,这也是一个非常糟糕的主意。只需在互斥体上使用'Object.wait()',并让按钮处理程序通知该互斥体。 –

+1

你应该使isYesButtonPressed(和isSendButtonPressed)'volatile' – ControlAltDel

回答

0

'The Infamous "Unresponsive User Interface"'说明如何使用Object.wait()Object.notify()跨线程进行通信。

Java存储模型允许现场更改不可见,除非该字段为volatile,所以改变非易失性boolean字段在UI线程不能保证使一个循环条件改变,直到这两个线程最终获得/释放锁定。

+0

谢谢,将布尔变量设置为volatile,它现在可以工作。尽管一个空的while循环会消耗大量的电池吗?这只是一个个人应用程序,没有什么重要的。 – Zezombye

+0

@Zezombye,请参阅[本文]的繁忙循环部分(https://software.intel.com/zh-cn/articles/benefitting-power-and-performance-sleep-loops) –

+0

另外,如果您需要做任何比写入System.out更复杂的东西,那么你可能需要同步一些共享对象。 –