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

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

提交回复
热议问题