我有一个服务器和两个客户端,服务器启动两个线程(ServerHandler),这两个线程都通过相应客户端的Socket
TCP连接传递,这些客户端在开始时就连接到服务器。
预期行为:一个ServerHandler线程将消息发送到客户端,而另一个ServerHandler线程等待wait()
...,然后工作线程通知正在休眠的线程并等待...等等。
实际行为:两个ServerHandlers同时等待。
ServerHandler的代码片段(正在运行两个实例)
@Override
public void run() {
System.out.println(String.format(" --> Server handler: %s is in run method...", serverID));
while (true) {
synchronized (this){
while (!Server.isFinished()) {
try {
System.out.println(String.format(" --> Server handler: %s is waiting...", serverID));
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println(String.format(" --> Server handler: %s is ready to send board...", serverID));
Server.setFinished(true);
sendBoard();
notify();
}
}
}
注意:Server
类同时启动两个ServerHandler线程。 finished
默认设置为false
输出:
CLIENT connected!
<-- I'M Alan I want to play!
--> Server handler 1 instantiated!
CLIENT connected!
<-- I'M Bot I want to play!
--> Server handler 2 instantiated!
HANDLER started...
HANDLER started...
--> Server handler: 1 is in run method...
--> Server handler: 2 is in run method...
--> Server handler: 1 is waiting...
--> Server handler: 2 is waiting...
预期的行为:
CLIENT connected!
<-- I'M Bot I want to play!
--> Server handler 1 instantiated!
CLIENT connected!
<-- I'M Alan I want to play!
--> Server handler 2 instantiated!
HANDLER started...
HANDLER started...
--> Server handler: 1 is in run method...
--> Server handler: 1 is waiting...
--> Server handler: 2 is in run method...
--> Server handler: 2 is ready to send board...
...
谢谢!
您能提供一些有关预期输出的示例吗?
似乎是一个偶然错误的事情是,两个线程都有自己的锁,而不是共享一个锁(请注意static。
没有意义的另一件事是在您已经拥有的锁上调用notify。
private static Object lock = new Object();
public void run() {
while (true) {
synchronized (lock) {
while (!Server.isFinished()) {
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
Server.setFinished(true);
sendBoard();
}
}
}