You are being forwarded to the lastest updates ot his page!
Or you can Click Here if it doesn't work or you don't wish to wait.

Use of threads in games

xmaspud
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.

code:

public class Breakout extends Applet implements Runnable, KeyListener, MouseListener {
....
public void init()
...
public void start()
{
th=new Thread(this);
th.start();
}
....
public void run()
{
// my game runs from here in a loop
}




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


psychohist@aol.com
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.


xmaspud
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 Bradley
So, I'm not very fluent in Applets.

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

code:

public class Breakout extends Applet implements Runnable, KeyListener, MouseListener {

....
public void init() {...}
public void start() {
th=new Thread(this);
th.start();
SpaceInvader spaceInvader = new SpaceInvader();
spaceInvader.start();
}
public void run(){
// my game runs from here in a loop
}
}
class SpaceInvader extends Thread {
public void run() {
// do space invader-ish stuff here
}
}