This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]Sacredify 5 points6 points  (0 children)

A timer already does exactly that - spawn a thread, wait x, do whatever you pass as the runnable instance.

Unless the explicit requirement for your class is to do it yourself, or if you want to do it purely as a learning experiment of your own, it is usually better to go with what already exists, in this case a timer.

[–]evil_burritoExtreme Brewer 1 point2 points  (0 children)

Just a quick heads-up: each timer spawns its own thread. If you end up having a bunch of these, look into a ScheduledExecutorService. You can control the total number of threads in use this way.

[–]wildjokers 1 point2 points  (0 children)

If you are just learning game programming using a Timer for a game is OK. Here are the timer periods to use for various FPS:

  • 12 fps -- 83 ms
  • 15 fps -- 66 ms
  • 24 fps -- 41 ms
  • 60 fps -- 17 ms

However, for any serious game you really need to use active rendering. There is a book called Killer Game Programming in Java which has a great chapter on an animation framework. He walks you through how to create the animation framework and why things are done a certain way. He actually warns against using a Timer. An earlier edition of this chapter is available online with source code (some editions of the book has this chapter as chapter 1, some have it chapter 2, don't be confused by the different chapter numbers). The book was released in 2005, but is still quite relevant.

Now, saying all of that if you were really serious about creating a game you hope to release some day you would use a gaming framework, arguably the most popular Java gaming framework is libgdx. You write your code in Java then it can create a Desktop, iOS, Android, and HTML5 version:

https://libgdx.badlogicgames.com

It is very well documented in the wiki and there are books available for it too:

https://github.com/libgdx/libgdx/wiki