如果在while true循环中有System.out.println(),则线程只能正确运行 [英] Thread only running correctly if there is a System.out.println() inside the while true loop

查看:187
本文介绍了如果在while true循环中有System.out.println(),则线程只能正确运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我正在制作一个更新玩家位置的游戏,它使用这个帖子:

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);
    }

}

哪个工作正常,但如果我删除System.out.println(),它停止运行。我不知道为什么会这样,全班如下:

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);
    }

}}

最后注释:填充布尔值upPresses和downPressed,我唯一关注的是:

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;
}


推荐答案



A loop like

while(true) {
    updatePos(x, y);
}

会完全占用CPU。使用 println 开始表现更好的原因可能是因为I / O每次迭代产生几百个周期。

would completely hog the CPU. Reason it starts behaving better with a println is probably because you yield a few hundred cycles per iteration for I/O.

我建议你根据所需的帧率添加一个小的睡眠方法:

I suggest you add a small sleep-method according to the desired frame rate:

while (true) {
    try {
        Thread.sleep(10); // for 100 FPS
    } catch (InterruptedException ignore) {
    }
    updatePos(x, y);
}

或更好的是采用事件驱动的方式例如 java.util.Timer中 。 (那将是更多Java-ish。)

or, even better, go with an event driven approach with for instance a java.util.Timer. (That would be more Java-ish.)

这篇关于如果在while true循环中有System.out.println(),则线程只能正确运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆