Java 等待和通知所有:IllegalMonitorStateException [英] Java wait and notifyAll: IllegalMonitorStateException

查看:53
本文介绍了Java 等待和通知所有:IllegalMonitorStateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Java 新手(也是 RoR 开发人员).

I am Java newbie (and RoR developer).

我有一个简单的程序.球在球员之间共享.球应该传递给随机玩家.

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

好的,代码如下:

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.

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

我该如何解决这个问题?

How can I fix this?

推荐答案

您正在等待 this 监视器而没有同步;你需要等待 ball 而不是

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

这篇关于Java 等待和通知所有:IllegalMonitorStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆