3

There probably is a very easy answer to this question but however I just don't get this because I just recently learned java. Take this simple code for example:

public class Test4 extends JFrame implements KeyListener {
public Test4(){
    super("Test");
    setSize(10,10);
    addKeyListener(this);
    setVisible(true);
}
static boolean test = true;
public static void main(String[] args){
    Test4 frame = new Test4();

    while(test){
        //When I put a System.out.println statement here it will print Testing or some other statement otherwise it will not print Testing.
    }
    System.out.println("Testing");
}

public void keyPressed(KeyEvent arg0) {
    int pressed = arg0.getKeyCode();

    if(pressed == 87){//w key
        test = false;
    }
}

Here is the problem I am having trouble with, without a statement in the while loop it will not print Testing when test = false, but with a statement it will go through the while loop and wait until test = false and then it will print Testing. Basically what this test program is trying to do is wait until you press the w key and then it will print out Testing but the while loop will only wait for the key to be pressed if there is a statement within it...I hope that made any sense. I know there are many other more efficient ways to make a program wait till a key is updated but this is just a test to see if a while loop works without any statements and currently it doesn't work unless there are statements I just want to know why. Thanks.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Lightning
  • 99
  • 9
  • 1
    To resume the duplicate, you need to declare your field as volatile so that is is visible for change to other threads, else the JVM will optimize into something like `if(boolean) { while(true); }` which causes an infinite loop no matter if the boolean is changed after. It still worth to read @Boann answer for example and details. – Jean-François Savard May 06 '15 at 23:45
  • Thank you for everybody that helped answer this question!!! – Lightning May 06 '15 at 23:49

0 Answers0