Omegalisk
Omegalisk

Reputation: 65

Should I use Thread.sleep to be nice to other programs?

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.

Upvotes: 2

Views: 368

Answers (2)

Amir Afghani
Amir Afghani

Reputation: 38541

I've had success building games that update the graphics using a Timer. Read up on the benefits here. In general though, Robert is correct, you don't need to do this. I find that usually comes down to finding a sweet spot int terms of the game animations FPS, not about being nice to other processes.

Upvotes: 4

Robert Harvey
Robert Harvey

Reputation: 180858

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.

Upvotes: 4

Related Questions