gpt4 book ai didi

Java等待和notifyAll : IllegalMonitorStateException

转载 作者:行者123 更新时间:2023-12-01 23:52:19 26 4
gpt4 key购买 nike

我是 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

我该如何解决这个问题?

最佳答案

您正在等待 this 监视器,但尚未对其进行同步;你需要等待而不是

关于Java等待和notifyAll : IllegalMonitorStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16155802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com