I have experienced weird behaviour while coding a simple game. Basically, I create a thread with an infinite loop that fires an event in my game every couple of seconds. With the Sysout(runAnimation) in place everything works fine. However as soon as I remove it the even stops occurring.
It appears that the system.out calll is affecting the behavior of the program, does anyone have an idea why this could be happening
Here is the loop:
private void run(){
long lastTime = -1;
while(true){
int timePerStep = (int) Math.ceil(ANIM_TIME/frequency);
System.out.println(runAnimation);
if(runAnimation && System.currentTimeMillis() - lastTime > timePerStep){
lastTime = System.currentTimeMillis();
controller.step();
try {
Thread.sleep(timePerStep);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
It’s started during the construction of my class as follows:
animThread = new Thread(new Runnable() {
@Override
public void run() {
GUIView.this.run();
}
});
animThread.start();
The
System.out.println()call issynchronized(mostPrintWritermethod calls are) so I suspect that there is something that you are not synchronizing on inside of your code. I wonder about therunAnimationfield. Could it be that it is set in another thread? Maybe it needs to bevolatile? Any field that is modified in one thread and read in another needs to besynchronizedorvolatile. Reading the Java thread tutorial around synchronization may help.Without seeing more of the code, it’s hard to put a finger on it but I suspect this answer will help anyway.
Lastly, do you really want your thread to spin until
runAnimationistrue? That’s a very bad practice. Maybe you should sleep for some time in the loop ifrunAnimationisfalseas well. Another idea is to use aCountDownLatchor other signaling mechanism to pause your thread until it needs to do the animation.