简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM