• Post Reply Bookmark Topic Watch Topic
  • New Topic

Multi Threading  RSS feed

 
chang lu
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi, i am doing a project and ran into a problem.

the goal of this program is to move a car and moon across the screen at the same time, but different speed.

here is a simplified version of my code:

drawCar // it draws the car
drawMoon // it draws the moon

goCar // it loops the drawCar method and increases the x coodinate by 1 each time, so it moves to the right
goMoon // it does the same thing as goCar but it moves the moon

now, i want the moon to go really slow, since 0.1 can't be used as a x coordinate, i used this time delay method:
public static void timeDelay (int seconds)
{
try
{
Thread.sleep (seconds);
}
catch (InterruptedException e)
{
//ignore
}
}

but now i dont know how to run both goCar and goMoon at the same time, i can't combine the 2 methods because the timedelay used to make the moon go slow will slow down the car as well. i think multi threading would work but all the things that i find about multithreading on the internet isn't making any sense towards what i am trying to do.

any help would be greatly appreciated
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello "clragon"-

Welcome to JavaRanch.

On your way in, you may have missed that we have a policy on screen names, and your does not conform to it. Please take a minute to read the policy and adjust your name here. Thanks for your attention to this.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One approach would be to create two classes -Car and Moon-, each of which implements the Runnable interface. That way you can start both of them as independent threads, and have them sleep at different times, and for different durations. If threads give you trouble in general, have a look ta the chapter on threads in Suns Java Tutorial.

There are of course other approaches that don't involve creating classes and threads.
 
chang lu
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for replying,and sorry about the name, the EULA just said "be nice" when i registered >.<

what other approach doesn't involve threads? because i used them only because i thought there were no other way to do it.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use the timeDelay method you already have, and then update the fast object every time, but update the slower object only every other time.

Or you could add only 0.5 to the coordinate of the slower object every time you add 1.0 to the coordinate of the faster one.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!