Click here to Skip to main content
15,882,278 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
Hello.
I want to move two spheres in java applet by assigning each sphere as a thread.
Is it possible?
With one thread its quite simple Iam just drawing the two balls, putting thread.sleep() and calling the repaint method, but can i implement each ball to be thread and move at the same time.
Posted
Updated 1-Jan-14 7:43am
v2
Comments
Sergey Alexandrovich Kryukov 1-Jan-14 13:43pm    
What have you tried so far?
—SA
missak boyajian 13-Jan-14 11:24am    
Well I know how to use threads but I dont know how to create two threads in applet that each must call the paint method in order to move. I am confused.

1 solution

Yes, this is of course possible.

Yes, you can even create a separate thread per each ball, but it might be not the optimal solution. For example, you cannot count on it if you want to have arbitrary number of moving spheres, say, configured by the user, because it would need too many threads, which would compromise performance. The most practical solution would be having exactly 2 threads: one is you UI threads, and another thread performs the motion of all the objects at once; call it "scenario" thread.

If you think about it, you will understand that kinematics works the way that only one thread for common scenario is needed. Here is what you do: the code of this thread runs in one loop, in each iteration, you first get the real time value from the clock. For this purpose, use the class org.apache.commons.lang.time.StopWatch:
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/StopWatch.html[^].

This will give you the time point for a given frame. It's important to measure real time, because threading will not guarantee your strictly periodic timing (and you never really need it for this task), but threading still much better than using timers, by a number of reasons. When you have time, you should calculate the position of each moving object it should take by that time, and take into account the collisions. And so on. I'll leave the rest of the solution for your home exercise.

Happy New Year!

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900