Thread only running correctly if there is a System.out.println() inside the while true loop

Basicly, I'm making a game which to update the players position, it uses this thread: @Override public void run() { while(true) { System.out.println(); updatePos(x, y); } } Which works fine, but if I remove the System.out.println(), it ceases to function. I have no idea why this is, the whole class is as follows: public class Player extends Block implements KeyListener, Runnable { int x; int y; int speed; boolean upPressed; boolean downPressed; boolean rightPressed; boolean leftPressed; static Sprite sprite = new Sprite("grass.png"); public Player(int x, int y, int speed) { super(x, y, sprite); this.x = x; this.y = y; this.speed = speed; Thread playerThread = new Thread(this, "Player Thread"); playerThread.start(); } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) { y -= speed; } if (e.getKeyCode() == KeyEvent.VK_DOWN) downPressed = true; if (e.getKeyCode() == KeyEvent.VK_RIGHT) rightPressed = true; if (e.getKeyCode() == KeyEvent.VK_LEFT) leftPressed = true; } @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) upPressed = false; if (e.getKeyCode() == KeyEvent.VK_DOWN) downPressed = false; if (e.getKeyCode() == KeyEvent.VK_RIGHT) rightPressed = false; if (e.getKeyCode() == KeyEvent.VK_LEFT) leftPressed = false; } @Override public void keyTyped(KeyEvent e) { } @Override public void run() { while(true) { System.out.println(); updatePos(x, y); } }} Final note: Ingore the boolean upPresses and downPressed, the only thing I'm focusing on is this: if (e.getKeyCode() == KeyEvent.VK_UP) { y -= speed; }

以上就是Thread only running correctly if there is a System.out.println() inside the while true loop的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏