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

后端 未结 5 2008
礼貌的吻别
礼貌的吻别 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:08

    A Thread.yield() can also do it in some cases. See https://www.javamex.com/tutorials/threads/yield.shtml for example. The author of this link does not recommend to use yield however.

    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2021-01-06 15:20

    Don't know if that would solve it, but it looks like you're giving the JVM a hard time... Try adding a short sleep (which is the correct way to implement a game thread) before each updatePos(x, y) call.

    @Override
    public void run() {
        while(true) {
        Try
        {
            Thread.sleep(50);
        }
        catch (Exception e){}
    
        updatePos(x, y);
        }
    

    }}

    0 讨论(0)
  • 2021-01-06 15:25

    You didn't post the code to updatePos. But at a minimum, you need to make that method, as well as keyPressed (and anything else that uses x and/or y) synchronized.

    Alternatively you can make both x and y volatile, but then x and y could get updated out of lockstep.

    But without any memory synchronisation, changes from one thread are not guaranteed to be observable from another thread.

    0 讨论(0)
  • 2021-01-06 15:28

    There is yet another appoach. You can use class java.util.Timer that is dedicated for implementation of scheduled tasks. It is very useful if for example you need now 2 threads that periodically perform some kind of different operations. Using Timer you can save your efforts and computer resources using only one thread

    0 讨论(0)
提交回复
热议问题