Java多线程服务器notify()IllegalMonitorStateException

时间:2014-06-22 16:10:39

标签: java wait notify

我有这段代码

    if( id == 0 ||(id % 2) != 0){
        System.out.println("test");
        synchronized(lock) {
            try {
                out1.println("Wait for another player...");
                lock.wait();
                System.out.println("lock");
          } catch (InterruptedException e) {
            e.printStackTrace();
            }
   some code here

}else{
        System.out.println("tes1t");
        player p2 = new player(id,socket);
        Players.add(p2);
        id++;
        lock.notify();  
    }

第一次运行客户端时,第一个代码块被执行并等待()直到另一个客户端连接。 当我运行第二个客户端,并尝试通知第一个代码块时,它向我显示此错误:

Exception in thread "NewPlayer1" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at tictactoe.ServerClass.run(ServerClass.java:129)

1 个答案:

答案 0 :(得分:1)

您必须在synchrnonized块中调用notify

synchronized(lock) {
    player p2 = new player(id,socket);
    Players.add(p2);
    id++;
    lock.notify();  
}