私は複数のボールが跳ねるという学校のプロジェクトに取り組んでいます。これまでのところ、私はアプリを作成することができ、すべてが正常に機能します。しかし、アプリにマルチスレッドを実装する必要もあり、これが行き詰まっています。私は1つのボールと1つのスレッドを考えていましたが、それをどのように実装するかがわかりません。これまでの私のコードは次のとおりです(一部):
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*/
}
}
}
クラスボール:
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) {}
}
}
スレッドのrun()関数にball.draw()関数を入れることができると思っていました。しかし、どうすればそれができるのか、それが良い考えかどうかはわかりません。マルチスレッドは、私が理解して実装するのがまだ難しいです=((