I have a program (an AWT Frame, yes I know that Swing is better but I am restricted from using it) that has 2 moving objects. So I thought I would put each in its own thread to allow the objects to move at different speeds, etc.
One thread (gameThread) handles a bouncing ball, and the other (cannonThread) handles a cannon drawn on the screen and the projectiles fired by it. I was unsure of how to seperate the ball’s speed and the projectile’s speed which is why I thought 2 threads would work (by using thread.sleep(speedofobject)).
I don’t know how to implement them and my random guess (obviously) didn’t work. Nothing shows up on the screen and there are no errors generated at compile time. Previously, the ball would show up on the screen and move around as it should.
Here’s a snippet from where I tried to do multiple threads. If you need more information, let me know and I’ll post it.
public void start()
{
if (gameThread == null)
{
gameThread = new Thread(this);
gameThread.start();
}
if (cannonThread == null)
{
cannonThread = new Thread(this);
cannonThread.start();
}
}
public void run()
{
//thread for the ball, collision detection and scorekeeping
if (Thread.currentThread().equals(gameThread))
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
while (!kill)
{
if (!paused)
{
target.repaint();
}
try
{
Thread.sleep(ballSpeed);
}
catch(InterruptedException e){System.err.println("Interrupted.");}
}
stop();
}
//thread for the cannon and projectile
if (Thread.currentThread().equals(cannonThread))
{
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
if (!paused)
{
if (projectileFiring)
{
cannon.repaint();
}
try
{
Thread.sleep(projectileSpeed);
}
catch(InterruptedException e){System.err.println("Interrupted.");}
}
}
}
Having a separate thread for each object in your world is not the way to go. One way to deal with this is to have a single separate thread that is responsible for updating the “world model” (in your case, the ball and the cannon). This world model thread would run the following animation loop:
Note that with this approach, you will need to synchronize access to the model data, because it will be updated by the animation loop in one thread and read by the rendering code to update the UI. You don’t want the data changing as you are reading it.