• Post Reply Bookmark Topic Watch Topic
  • New Topic

1 thread running with 4 subthreads  RSS feed

 
bab javier
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
let's say i have 4 cirlces spinning at the same time. can i vary the speed of each one and then all of them spinning at the same time?
with 4 different threads, its possible. but to have it running under 1 thread.....
pls help...thanks
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it's possible. The details will probably depend on how you handle the graphics of making a circle rotate. (Hopefully the circle has some visual features which make it so you can tell it's spinning, since a plain circle looks much the same when it's spinning as when it's not.) I'd suggest using a java.util.Timer - for each circle, create a TimerTask which can repeatedly update the orientation of the circle's image - so that each time the TimerTask is run, it turns the circle a little bit. Then call
Timer.scheduleAtFixedRate(TimerTask tt, long period, long delay)
to start that circle in motion, running the TimerTask at a given period which is inversely proportional to the speed you want the circle to rotate at. Each circle can have a separate TimerTask which fires at a different rate than the others; all those TimerTasks can run in the same Timer, which internally uses a single thread to keep track of all the events that have been scheduled.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For each disk, you need an equation for the rotation angle as a function of time; for a constant rotational speed, the equation is just
angle = k * time;
where k is a constant; smaller values of k give slower disks. Each disk has its own unique value of k; changing the value of k for a disk changes its rotation speed.
Your single thread would have a loop. In the loop, you'd do the following work:
  • Check the time with System.currentTimeMillis();
  • For each disk, compute the appropriate rotation angle and store them all in an array.
  • Call repaint();
  • Sleep for some period of time.
    In your paint() method, for each disk, fetch the stored rotation angle and draw it. Each disk appears to rotate independently, at its own speed.

  • OK?
     
    bab javier
    Ranch Hand
    Posts: 32
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    got it and combined ur suggestions. although, i minimized the use of method calls (i use J2ME ). its working now
    thanks guys!
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!