Java wait and notifyAll: IllegalMonitorStateException

不想你离开。 提交于 2019-12-20 07:27:03

问题


I am Java newbie (and RoR developer).

I have a simple program. Ball is shared amont players. Ball should be passed to random Player.

Ok here goes the code:

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() );
        }
    }
}

But it doesn't work. I get exception: IllegalMonitorStateException.

How can I fix this?


回答1:


You're waiting on the this monitor without having synchronized on it; you need to wait on ball instead



来源:https://stackoverflow.com/questions/16155802/java-wait-and-notifyall-illegalmonitorstateexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!