我正在尝试使用“synchronized(object) {object.wait()}
”来暂停我的服务器,直到对象准备就绪。我在类中调用了“synchronized(object) {object.notify() }
”来设置对象值。但似乎我的服务器在 wait()
之后就再也没有醒来过。
public class MyServer {
...
do {
try {
message = (String) in.readObject();
System.out.println("server receive>" + message);
synchronized (myServerSend) {
myServerSend.wait();
}
System.out.println("Am I wake up???"); //this never print out
sendMessage(myServerSend);
} catch (ClassNotFoundException classnot) {
System.err.println("Data received in unknown format");
}
} while (!message.equals("bye"));
} catch (IOException ioException) {
ioException.printStackTrace();
}
....
}
这是我对设置对象值的调用
public class Action implements MouseInputListener, MouseMotionListener {
....
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {...
}
else {
....
if(MyGame.currentPlayer == MyGame.WHITE) {
myServerSend = "" + chosenPieceIndex + "," + moveLocationIndex;
synchronized (myServerSend) {
myServerSend.notify(); // this seems like fail to wake up myServer
}
System.out.println(myServerSend);
}
如果我将 myServerSend 声明为公共(public)静态字符串类型会有问题吗? 有人可以帮忙吗?提前致谢!
最佳答案
也许您在等待之前就得到了通知代码。出于这个原因,您应该始终将 thread.wait() 放在 while 循环内(也由于虚假唤醒 - 但出于这个原因, do while 就足够了)。
关于java - object.notify() 不会唤醒 object.wait(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14883475/