Thread.sleep is iirc only accurate down to 5msec. There may be platforms with higher accuracy, but I wouldn’t rely on that.
Here’s the code of my sync2 method. sync2b is the same, but it uses sleep if there are more than 5msec to waste. Both should be called with hz+1 as parameter.
public static void sync2(long fps)
{
long gapTo = Sys.getTimerResolution() / fps + timeThen;
timeNow = Sys.getTime();
while(gapTo > timeNow+timeLate)
{
Thread.yield();
timeNow = Sys.getTime();
}
if(gapTo<timeNow)
timeLate = timeNow-gapTo;
else
timeLate = 0;
timeThen = timeNow;
}
public static void sync2b(long fps)
{
long gapTo = Sys.getTimerResolution() / fps + timeThen;
timeNow = Sys.getTime();
while(gapTo > timeNow+timeLate)
{
if(gapTo > timeNow+timeLate+5000L)
Thread.sleep(5);
else
Thread.yield();
timeNow = Sys.getTime();
}
if(gapTo<timeNow)
timeLate = timeNow-gapTo;
else
timeLate = 0;
timeThen = timeNow;
}