Reputation: 51
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 =((
Upvotes: 1
Views: 224
Reputation: 12269
All swing code has to run on the event dispatching thread. Therefore what you're doing in the code snippets is bad.
However, if calculating ball positions is cpu intensive and requires time, you do want to move the logic in a separate thread, otherwise your UI will become unresponsive.
This would become a typical producer/consumer problem: one thread produces cooridnates and the event dispatch thread consumes them by drawing the balls.
Upvotes: 1
Reputation: 36601
Not a real answer, but too long to put in a comment.
You should note that Swing is not thread-safe. All Swing components should be accessed on the Event Dispatch Thread, and on that thread only. See the Concurrency in Swing guide for more information.
This means that you can have one thread per ball which updates the position of the ball. However, if you access the position of the ball during the painting, this access happens on the EDT. Meaning that you cannot update the position of the ball in your background thread at any moment. You will have to implement some locking or simply update the position on the EDT.
I am not sure what you try to achieve, but if you simply want to update the position of a ball at certain time intervals I would opt for a javax.swing.Timer
. This timer is triggered on the EDT, allowing you to update the position in a thread-safe manner. The Swing wiki tag contains some more links for implementing animation in Swing.
Upvotes: 2