I am working on a school project about multiple balls bouncing. So far, I managed to create the app and everything works ok. But, I also need to implement multi-threading in the app, and this is where I am stuck. I was thinking of one ball one thread, but I am not sure of how to implement it. Here is my code so far (part):
public void paintComponent(Graphics g)
{
super.paintComponent(g);
//The balls are painted only after the timer is started
if(bTimer)
{
for(Ball ball:ballList.ballsArrayList)
{
Thread ballThread = new Thread(ball);
ballThread.start();
ball.draw(g);
/*other code for moving the ball*/
}
}
}
In the class Ball:
public void draw(Graphics g) {
Color color = new Color(this.getColorR(),this.getColorG(),this.getColorB());
g.setColor(color);
int radius = this.getsize();
g.fillOval((int)(this.getX() - radius), (int)(this.getY() - radius), (int)(2 *
radius), (int)(2 * radius));
}
public void run() {
String name = Thread.currentThread().getName();
for (int i = 0; i < 200; i++) {
//ball.draw(g); ??
try {
Thread.sleep(50);
System.out.println("Sleeping");
} catch (Exception ex) {}
}
}
I was thinking that I could put the ball.draw() function in the run() function for the thread. But I don't know how I can do that or if it's a good idea. Multi-threading is still difficult for me to understand and implement =((