0

I want to have a thread that loops at a constant amount of times per second for example a render loop that aims for a constant framerate. The loop would obviously slow if the time it takes exceeds the time allowed.

Thanks.

3
  • 1
    Measure the time you need for the current loop, take your constant time and substract the measured time, let the thread sleep for the rest. Commented Feb 1, 2014 at 9:40
  • I have not tried anything yet, I was thinking of just using thread.sleep but that would not make the best use of the available time. Commented Feb 1, 2014 at 9:41
  • 1
    What else would you need to do after the frame is rendered then? Commented Feb 1, 2014 at 9:43

2 Answers 2

3

How about

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(0, delay, TimeUnit.MILLI_SECONDS, new Runnable() {
     public void run() {
         // do something
     }
});

or

long delay = .... 
long next = System.currentTimeMillis();
while(running) {
     // do something
     next += delay;
     long sleep = next - System.currentTimeMillis();
     if (sleep > 0)
          Thread.sleep(sleep);
}
Sign up to request clarification or add additional context in comments.

3 Comments

That Thread.sleep should be in a try-catch block no? InterruptedExceptions and all that...
What would happen if for example the system clock was set a hour back?
@user2248702 In the second case, this would mean that nothing would happen for an hour. Note: this is not the same as the end of daylight savings as this doesn't change the GMT time. If you concerned about this you can use System.nanoTime() like the ScheduledExecutorService does.
0

There are two basic techniques you need two consider:

  1. seperate updateing your model or state of the world from rendering it.
  2. If you have done that, you can sleep/wait the appropriate amount of time before rendering stuff or skip the rendering for some frames if you fall behind your planed schedule.

I can recommend two good tututorials on how to implement something like a game loop in java/android. First one about the basics is http://obviam.net/index.php/a-very-basic-the-game-loop-for-android/ and the second one has a focus on constant Frames per Second: http://obviam.net/index.php/the-android-game-loop/. I think the lessons apply to regualar java as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.