简体   繁体   English

Java多线程服务器notify()IllegalMonitorStateException

[英]Java multi-threaded Server notify() IllegalMonitorStateException

I have this code 我有这个代码

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

The first time i run the client, the first block of code gets executed and it waits() until one more client gets connected. 第一次运行客户端时,将执行第一个代码块,并且它等待()直到连接了另一个客户端。 When i run the second client, and i try to notify the first block of code, it shows to me this error: 当我运行第二个客户端时,我尝试通知第一段代码,它向我显示此错误:

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

You have to call notify in synchrnonized block 您必须在同步块中调用notify

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM