Java Snake Game Avoid Using Thread.sleep

I made my first Java game - Snake, this main loop looks like this:

while (true) { long start = System.nanoTime(); model.eUpdate(); if (model.hasElapsedCycle()) { model.updateGame(); } view.refresh(); long delta = (System.nanoTime() - start) / 1000000L; if (delta < model.getFrameTime()) { try { Thread.sleep(model.getFrameTime() - delta); } catch (Exception e) { e.printStackTrace(); } } } 

But there is a response point in my project requirements, so I need to change Thread.sleep() to something else, but I have no idea how to do this in a simple way. Thanks in advance for any advice.

+5
source share
2 answers

I made a simple game or two with Java and I used Swing Timer to handle the main game loop. A timer allows you to set an ActionListener that will be started after the expiration of the provided delay . The intermediate delay will be obtained from your frame rate. The most basic use would look like this:

 Timer timer = new Timer(delay, listener); timer.start(); 

This would set the initial and intermediate delays to the same value. You can also set different values ​​for them, if necessary:

 Timer timer = new Timer(delay, listener); timer.setInitialDelay(0); timer.start(); 

In the above example, the listener will start as soon as possible after starting and with a delay between them.

+3
source

It is best to use a timer, as suggested above, which allows you to start after the specified delay without calling sleep ().

if you want this to be a little trickier, but the self-made start of a new thread for sleep processing. You can put the join mechanism at some pool frequency to avoid thread.sleep.Put your condition during the loop and wait for some tine if the condition is not met. And the waiting time should be less, so it will interrogate with a small interval.

 //more code here It is a sample code synchronized(this) { while (delta < model.getFrameTime()) { this.wait(500); } //more code 
-1
source

Source: https://habr.com/ru/post/1268736/


All Articles