Hi all
Suppose I have a main method that do the following:
Ball [] ball = new Ball[5];
private int numOfball = 10;
for (int i = 0; i < ball.length i++)
{
ball[i] = new Ball(i,numOfball);
ball[i].start();
numOfball= ball.getNum();
}
Inside the Ball class I have the following:
public class Ball extends Thread
{
private static int numOfball;
private int id;
public Ball(int id,int numOfball)
{
this.id = id;
this.numOfball = numOfball;
}
public synchronized int getNum()
{
System.out.println("Number left:" + numOfball);
if(numOfball>0)
{
System.out.println("Ball" + id + " throw);
Thread.sleep(id);
numOfball--;
System.out.println("Ball " + id + " return." );
}else
{
System.out.println( "There are no more ball!" );
numOfball = 10;
}
return numOfball;
}
public void run()
{
getNum();
}
}
Each time I call the ball class in my main method, the numOfball seem to be the same for a few times.May I know how to make the numOfball in the Ball class such that it will be synchronized and not repeated?
Thank you.