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.
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.
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);
}
Thread.sleep should be in a try-catch block no? InterruptedExceptions and all that...There are two basic techniques you need two consider:
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.