【问题标题】:Why if block doesn't work [duplicate]为什么如果块不起作用[重复]
【发布时间】:2017-11-22 22:20:12
【问题描述】:
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是一个全局变量,初始值为false。通常,当我点击左、右、上或下按钮时,gameStart 变量设置为 true,但 if(gameStart) 不起作用。但是当我用注释块放慢速度时, if(gameStart) 运行正常。为什么会这样?

【问题讨论】:

  • 在触发 keyListener 和评估该条件之间似乎存在某种竞争条件。

标签: java if-statement keylistener


【解决方案1】:

您可能正面临所谓的“竞争条件”。在这里查找:Race-Condition-Example

您为什么不直接使用break 离开while 循环?

这应该适合你:

if (gameStart) {
    start();
    break;            
}

【讨论】:

    猜你喜欢
    • 2016-03-20
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 2015-07-06
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多