I usually write (smallish) games in Java using a main ‘while’ loop somewhat like this:
while(running) {
time = getTime();
if(time - oldTime > 0.01) {
tick(time - oldTime);
oldTime = getTime();
}
}
I do this to make the program have a maximum number of frames per second, but I’ve heard that Thread.sleep allows other threads to execute. Should I add in a Thread.sleep(1) (or some other low number of milliseconds) to allow other threads on the computer? It’s more a question of good programming practice than performance, and it isn’t really necessary, but I like making reliable and ungreedy programs.
No, you don’t need to do this.
All modern preemptive multitasking systems allocate time to other threads to allow them to execute. You don’t need to
sleep()to accomodate this, unless you want to forcibly relinquish control to other threads for a certain period of time.The only time you might want to do this is if you are hogging all of the cores on a multi-core system, and you want a long-running, computationally-intensive task to complete quietly in the background without discernibly affecting other operations taking place concurrently.