This is a simple animation framework made for Java. The framework supports both frame skips and thread yielding, and is a great conceptual starting point.
private static final int MAX_FRAME_SKIPS = 10;
private static final int NO_DELAYS_PER_YIELD = 16;
private static final int period = 33; // 1000/[desired FPS]
private volatile boolean running = true; // dynamically changing variable
public void run( ){
long beforeTime, afterTime, timeDiff, sleepTime;
long overSleepTime = 0L;
int noDelays = 0;
long excess = 0L;
beforeTime = System.nanoTime();
running = true;
while(running) {
gameUpdate( );
gameRender( );
paintScreen( );
afterTime = System.nanoTime();
timeDiff = afterTime - beforeTime;
sleepTime = (period - timeDiff) - overSleepTime;
if (sleepTime > 0) { // some time left in this cycle
try {
Thread.sleep(sleepTime/1000000L); // nano -> ms
}
catch(InterruptedException ex){}
overSleepTime =
(System.nanoTime() - afterTime) - sleepTime;
}
else { // sleepTime <= 0; frame took longer than the period
excess -= sleepTime; // store excess time value
overSleepTime = 0L;
if (++noDelays >= NO_DELAYS_PER_YIELD) {
Thread.yield( ); // give another thread a chance to run
noDelays = 0;
}
}
beforeTime = System.nanoTime();
/* If frame animation is taking too long, update the game state
without rendering it, to get the updates/sec nearer to
the required FPS. */
int skips = 0;
while((excess > period) && (skips < MAX_FRAME_SKIPS)) {
excess -= period;
gameUpdate( ); // update state but don't render
skips++;
}
}
System.exit(0);
} // end of run( )