Search code examples
javasleepgame-loop

Java - How to block a running thread for an exact amount of time?


I need my main Thread to block for a specific amount of time. I am currently working on a 2D game and it's pretty laggy just because the Thread.sleep(2) sleeps for ~17 seconds and when you move the character, graphics are lagging slightly. Sometimes it's working just fine (when I ran the application about 10 times) and sometimes it's not. I know that there is a delay on the Thread.sleep(long milliseconds) method but is there any way to avoid it or an alternative? I already tried LockSupport.parkNanos((long)2e6) but that didn't change anything.


Solution

  • What you are looking for is the 'game loop' pattern. This explains it pretty well... http://www.java-gaming.org/index.php/topic,24220.0