¿Debo usar Thread.sleep para ser amable con otros programas?

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.

preguntado el 30 de junio de 12 a las 23:06

Well it depends. Are you planning to do some other heavy computations while your game is running? -

2 Respuestas

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.

Respondido el 30 de junio de 12 a las 23:06

Additionally, Thread.sleep() only really affects other threads in the same VM. not other apps. For other apps, the OS scheduler is probably good enough to ensure fairness. - Jochen

I've had success building games that update the graphics using a Minutero. Read up on the benefits aquí. In general though, Robert is correct, you don't necesitas 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.

contestado el 23 de mayo de 17 a las 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.