While loop not ending when flag changed in different thread
===

I have a while loop running in my Java program's main method. The loop is supposed to run until a boolean flag variable is set to true in the program's keyPressed method (I added the program as a KeyListener to a JFrame). 


    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JFrame;

    public class ThreadWhile implements KeyListener {
        private boolean flag = false;

	    public static void main(String[] args) {
		    //Set up key listening on a dummy JFrame
		    JFrame frame = new JFrame("Key Detector 9000");
		    frame.setVisible(true);
		    ThreadWhile tw = new ThreadWhile();
		    frame.addKeyListener(tw);
		
		    System.out.println("Looping until flag becomes true...");
		    while(!tw.flag) {
			    //Commenting the println out makes the loop run forever!
			    System.out.println(tw.flag); 
		    }
		    System.out.println("Flag is true, so loop terminated.");
		    System.exit(0);
	    }

	    public void keyPressed(KeyEvent e) {
		    flag = true;
		    System.out.println("flag: " + flag);
	    }
	
	    public void keyReleased(KeyEvent e) {}
	    public void keyTyped(KeyEvent e) {}
    }



It is my understanding that keyPressed methods execute in their own threads, so it seems like when I hit a key, the variable 'flag' should be set to true, and the while loop running in the main method should end. 

HOWEVER, when I run this program, the loop runs forever, even though we can see that the 'flag' variable is being set to true correctly! Oddly, the program behaves correctly if I insert a quick System.out.println echo of the 'flag' variable inside the while loop, but obviously I don't want to print anything out in the loop.

I'm guessing this problem might be a result of the Java compiler trying to optimize the empty while loop to the point where it stops actually checking the 'flag' variable? Does anyone have suggestions for making this work correctly, or perhaps some more nifty concurrency-based approaches to making the main thread pause until the keyPressed thread executes?

Thanks!