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

后端 未结 5 2012
礼貌的吻别
礼貌的吻别 2021-01-06 14:38

Basicly, I\'m making a game which to update the players position, it uses this thread:

@Override
public void run() {
    while(true) {
        System.out.pri         


        
5条回答
  •  广开言路
    2021-01-06 15:11

    A loop like

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

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

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

提交回复
热议问题