我是Java新手(和RoR开发人员)。
我有一个简单的程序。 球是共享的球员。球应该传递给随机球员。
好的,这里是代码:
class Ball {
private int currentPlayer;
public void setCurrentPlayer( int currentPlayer, int fromWho ) {
this.currentPlayer = currentPlayer;
System.out.println( "Ball:setCurrentPlayer " + fromWho + " ---> " + currentPlayer );
}
public int getCurrentPlayer() {
return currentPlayer;
}
}
class Player implements Runnable {
private int myID;
private Ball ball;
private int playersCount;
java.util.Random rnd;
public Player(int id, Ball ball, int playersCount) {
myID = id;
this.ball = ball;
this.playersCount = playersCount;
rnd = new java.util.Random( id );
}
public void run() {
int nextPlayer;
while (true) {
synchronized (ball) {
if ( ball.getCurrentPlayer() == myID ) {
nextPlayer = rnd.nextInt(playersCount);
System.out.println( "Player nr. " + myID + " ---> " + nextPlayer );
ball.setCurrentPlayer( nextPlayer, myID );
ball.notifyAll();
} else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class Start {
public static void main( String[] argv ) throws Exception {
Ball p = new Ball();
System.out.println("MAIN: ball will be in player: " + p.getCurrentPlayer());
final int playersCount = 5;
for ( int i = 0; i < playersCount; i++ ) {
( new Thread( new Player( i, p, playersCount ) ) ).start();
}
while ( true ) {
Thread.sleep( 500 );
System.out.println( "MAIN: ball is in player : " + p.getCurrentPlayer() );
}
}
}
但它不起作用。
我得到例外:IllegalMonitorStateException
。
我该如何解决这个问题?
答案 0 :(得分:3)
你正在this
监视器上等待而没有同步它;您需要等待ball
而不是