Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Use of threads in games

 
Martin Platt
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

As a relative newbie to programming in Java, I was wondering if anyone can give me some advice on using threads.

I wrote a simple bat'n'ball applet last week, to which I have now added a Brick class and turned it into a breakout game. I've done all this within one thread. e.g.



At the moment, everything is done in the run() method's game loop, i.e. it draws the ball, the bat, loops round checking for collisions with bricks...

Question 1

Suppose I wanted to go on developing this game, making it more sophisticated. Lets say I introduce all sorts of AI-controlled space invader sprites as well as lots of other impressive things. Do I carry on adding more and more to this game loop or would I reach a point when starting a new thread would be a better option? If so, why?, and how do I decide when to start a new thread?

Question 2

Within my applet set-up, how do I start a new thread? Suppose I wanted a new thread solely for animating alien sprites. How can I create it - I've only got room for one run() method, haven't I?

Sorry if these questions are quite basic


MP
 
Warren Dew
blacksmith
Ranch Hand
Posts: 1332
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Martin Platt:

Do I carry on adding more and more to this game loop or would I reach a point when starting a new thread would be a better option? If so, why?, and how do I decide when to start a new thread?

The basic reasons for using multiple threads are:

(1) To take advantage of the processing power of multiple processors. This is unlikely to be an issue for most games.

(2) To simplify programming of long tasks that need to be interruptible by shorter term tasks. For example, a video rendering program might want to allow the user to do stuff while rendering a video in the background; this can be cleaner if you use a separate thread for rendering. This is slightly more likely to be applicable to a game.
 
Martin Platt
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. But how do I start a new thread when my Main class only has room for one run() method??

I hope someone can explain this for me.
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, I'm not very fluent in Applets.

Is it possible to create a new class that extends Thread and call its start method?

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic