问题
I have noticed something very odd (which eventually crashes my game) with Thread.sleep()
and I cannot figure out what the problem might be. I have run the following method for two hours straight and the output is always 100+-5;
public void gameLoop() {
t0 = time();
while (GameState.getInstance().getState() == GameCondition.RUNNING) {
engine.update();
sfx.play();
t1 = time();
delta = t1 - t0;
gfx.render((int) delta);
t0 = time();
System.out.println(delta);
sleep(100);
}
}
Now if I run the exact same method but instead of sleeping for the constant 100 I sleep for delta
public void gameLoop() {
t0 = time();
while (GameState.getInstance().getState() == GameCondition.RUNNING) {
engine.update();
sfx.play();
t1 = time();
delta = t1 - t0;
gfx.render((int) delta);
t0 = time();
System.out.println(delta);
sleep(delta);
}
}
And now the output reads:
0
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
2
....
After a minute
571
I don't know if I am too tired and have made an obvious mistake or something very weird is happening, here is the sleep.
private void sleep(long milliSeconds) {
System.out.println();
try {
Thread.sleep(milliSeconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Edit: The problem? The delta is "leaking", since the inner methods (before the sleep) use virtually no time (as proven by the sleep(100)
test) I expect delta to be very precise with minor to no fluctuations, yet it keeps growing.
回答1:
In your loop, your delta calculation encompasses the time previously slept, and then sleeps for this new delta time. If sleep (or your code) is ever slow (say 1ms, which can happen) then your delta will be 1ms longer next time so you will sleep for 2ms.
Your next iteration, since you slept for 2ms last time, will be at least 2ms. If sleep or your code is slow again (which will happen) then you will sleep for 3ms next time and so on. You are accumulating all the slowness that might occur due to your delta including the previous sleep time and any error in it.
来源:https://stackoverflow.com/questions/15960607/weird-behavior-in-thread-sleep