I’m having trouble with Thread.sleep(). I’m telling it to sleep 16.666667 milliseconds, but it seems like every 7th-10th call it sleeps for twice as long.
Here’s the code:
public void run() {
try {
double sleepTime = 16.666667;
while( true ) {
timeStep();
int milli = (int)sleepTime;
int nano = (int)((sleepTime - milli)*1000000);
long startSleep = System.currentTimeMillis();
Thread.sleep( milli, nano );
long finishSleep = System.currentTimeMillis();
System.out.println(finishSleep - startSleep);
}
}catch( InterruptedException e ) {
//TODO: Crash Nicely
System.out.println("Crashed in Game Loop");
e.printStackTrace();
System.exit(1);
}
}
I’ve simplified it in some places that don’t matter. The important part is this:
long startSleep = System.currentTimeMillis();//This is debug code
Thread.sleep( milli, nano );
long finishSleep = System.currentTimeMillis();//This is debug code
System.out.println(finishSleep - startSleep);//this is debug code
I expect that this will print 16-17 everytime it prints. Maybe sometimes 14-18. Small variances wouldn’t make much of a difference, but huge ones do. This is the output I get:
[quote]31
16
15
16
16
15
16
16
31
15
16
16
15
16
16
15
31
16
16
15
16
16
15
16
31
16
15
16
16
15
16
31
16
15
16
[/quote]
You can see that every 10 frames or so it’s sleeping for what appears to be about twice as long. Does anyone have any idea why this is happening? I can develop a really crappy work around, but I’d rather not have to. Any ideas would be appreciated.
Thanks,
-Josh