In this example, I have a simple JFrame containing a JButton bound to an ActionListener. This AcitonListener simply changes the boolean flag, which should allow the program to terminate.
public class Test { public static void main(String[] args){ final boolean[] flag = new boolean[1]; flag[0] = false; JFrame myFrame = new JFrame("Test"); JButton myButton = new JButton("Click Me!"); myButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { System.out.println("Button was clicked!"); flag[0] = true; } }); myFrame.add(myButton); myFrame.setSize(128,128); myFrame.setVisible(true); System.out.println("Waiting"); while(!flag[0]){} System.out.println("Finished"); } }
It never prints "Finished", and after clicking the button after printing
Waiting Button was clicked!
However, if I change the while loop to read
while(!flag[0]){ System.out.println("I should do nothing. I am just a print statement."); }
It works! The printout looks like
Waiting I should do nothing. I am just a print statement. I should do nothing. I am just a print statement. .... I should do nothing. I am just a print statement. Button was clicked! Finished
I understand that this is probably not the way to wait for action, but nonetheless, I am interested to know why Java behaves in this way.
Aroto source share