public void sleepUntil(long time)
{
while(System.currentTimeMillis() < time) Thread.yield();
}
By yielding instead of sleeping, the method will return almost to the moment the clock flips over to match the “time” variable. The only problem is that it will use 100% of the CPU to do it. Of course, this isn’t a big deal as the method is actually giving up its time to other processes, but anything that the other processes don’t use will come right back to that loop.
This method is particularly advantageous when dealing with the System.currentTimeMillis() timer. For example, if I’m deploying my game on Windows 2000, System.currentTimeMillis() gives a tick rate of 100 ticks per second. If we use Thread.sleep(), we have no idea how many milliseconds we have until the next tick. This means that the framerate may jump all over the place as we’ll have no idea how often we need to sleep, or for how long. But if we latch onto the digital wave generated by the clock, we can always guarantee exactly 10ms to render each frame. Extra time can be slept off by waiting for the next clock tick.
Here’s a graph to demonstrate:
-- -- --
|__| |__|
^ ^ ^ ^
| | | |
begin rendering
Make sense?