-2
boolean gameContinues = true;
gameWindow.addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() >= KeyEvent.VK_LEFT && e.getKeyCode() <= KeyEvent.VK_DOWN) {
            directionGoing = e.getKeyCode() - KeyEvent.VK_LEFT;
            gameStart = true;
        }
    }
});

while (gameContinues) {
//  for(int i = 0; i < 1000000000; i++) {
//      for(int j = 0; j < 1000000000; j++) {
//          
//      }   
//  }
    if (gameStart) {
        start();
        gameContinues = false;              
    }
}

private void start() {
    // game operations
    System.out.println("started");
}

gameStart is a global variable, and initial value is false. Normally, when I hit left, right, up or down buttons, gameStart variable sets true, but if(gameStart) doesn't work. But when I slow down with the commented for blocks, if(gameStart) runs properly. Why this happens?

  • 1
    It seems like you have some sort of race condition between the keyListener being triggered and that condition being evaluated. – braden.groom Nov 22 '17 at 22:24

1 Answers1

0

Probably you are facing a so called 'race condition'. Look it up here: Race-Condition-Example

Why wouldn't you just use break to leave the while loop?

This should work for you:

if (gameStart) {
    start();
    break;            
}
oRole
  • 1,316
  • 1
  • 8
  • 24