|
|
|||||||||
|
|||||||||
|
|||||||||
| |
|||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Thread.sleep() - Problems
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: Code:
public void run() {
try {
double sleepTime;
while( true ) {
timeStep();
sleepTime = 16.666667;
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: Code:
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. But this is the output I get: Quote:
You can see that every 10 frames or so it's sleeping for what appears to be exactly twice as long (16.66667 * 2 is going to round to 31 almost every time). 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 |
|
#2
|
|||
|
|||
|
Sorry for answering so long after you posted. This isn't a solution, but I thought of something you could do to get more information about the problem.
Try the same code with different sleep times, to be sure the frames in question are always twice as long, or if it is just a cooincidence with the value 16.66... This will also tell you if the problem happens more or less often for large or small values, or if it is the same for all. This could be an issue of Java being busy with another thread and not getting back to your thread fast enough, but I don't know a lot about how Java handles threads. |
![]() |
| Viewing: Dev Articles Community Forums > Programming > Java Development > Thread.sleep() - Problems |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|