This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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...
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?
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?
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.
Joined: Aug 23, 2004
Thanks. But how do I start a new thread when my Main class only has room for one run() method??