I tried several methods, and yield makes no sense in a game loop. It tells the scheduler that works it’s doing is not that important and that it can go ahead and move to the next time slice. What I do in my tight render loop is lock it at a max of 59.9something FPS:
public void run() {
while (_running) {
final long newTime = System.currentTimeMillis();
if ((newTime - _lastProcessed) < GAME_MINFRAMETIME) {
try {
Thread.sleep((long) (GAME_MINFRAMETIME - (newTime - _lastProcessed)));
} catch (final InterruptedException e) {
e.printStackTrace();
}
continue;
}
_lastProcessed = newTime;
try {
renderGraphics();
handleMessages();
if (_currentScreen != null) {
_currentScreen.update();
}
} catch (final Exception e) {
e.printStackTrace();
stop();
}
}
}
This slows the thread down if it’s running 60+ fps. When I look in the profiler it shows the thread obediently sleeping when needed, allowing other threaded loops to execute before returning back to the render logic.
Thread.Sleep tells the system to not execute the thread for x amount of time – this means it literally gives absolutely 0 CPU time to the thread until the time has passed (this is an operating system related thing). I highly prefer thread.sleep when used properly.