Search code examples
javagame-enginetimingframe-ratethread-sleep

while loop or Thread.sleep()?


I'm programming a game in Java and I limit the FPS to 60. I figured out 2 different ways to get the same result, but I'm wondering which of them is the better/cleaner way to do it. Or maybe you have a different idea.

while(System.nanoTime() - thisFrame < fps_limit);

or

Thread.sleep(sleepingTime);

My thinking is that the while loop effects the CPU more than Thread.sleep, am I right?

Thanks in advance for your help!

Dom


Solution

  • You have the following main options:

    1. While loop - This will consume CPU cycles and often will actually stop the system because while you are looping, other threads cannot run (on a one-core machine).
    2. Thread.sleep() - This can be effective but you need to remember that is not guaranteed to wait the specified time.
    3. DelayQueue - More up-to-date. Better/accurate timing.
    4. ScheduledThreadPoolExecutor - Still more up-to-date than DelayQueue. Uses a Thread Pool.