【发布时间】:2016-01-03 23:06:12
【问题描述】:
更新: 事实证明我的 Synchronized 语句没有任何问题。我早些时候在代码中犯了一个错误,它在那里被阻塞了。对于浪费的时间,我深表歉意,并感谢您提供的所有帮助。
PS。 @sh0rug0ru 建议的 CountDownLatch 更适合我的需求,正是我所需要的。
上一个:
这是代码的相关部分:
synchronized (readyLock) { //sets this thread's status to ready
readyLock.notify();
System.out.println("notify works");
try {
readyLock.wait();
System.out.println("woke up from sleep");
} catch (InterruptedException ex) {
Logger.getLogger(Battleship_server_clientThread.class.getName()).log(Level.SEVERE, null, ex);
}
readyLock.notify();
}
while (true) { //game loop
//Some stuff here
synchronized (readyLock) { //sets this thread's status to ready
readyLock.notify();
System.out.println("notify works");
try {
readyLock.wait();
System.out.println("woke up from sleep");
} catch (InterruptedException ex) {
Logger.getLogger(Battleship_server_clientThread.class.getName()).log(Level.SEVERE, null, ex);
}
readyLock.notify();
}
//Some more stuff here
}
readyLock 对象在另一个类中初始化为静态最终变量:
static final Object readyLock = new Object();
Synchronized 语句第一次工作,就像在第一个同步语句块中一样。但是 while 循环内的同步块不起作用。这两个地方的代码完全相同。
此类是从服务器运行两次的线程。这是一个两人游戏。其余代码为here。
我试图弄清楚为什么第二个同步语句不起作用。我认为它只是出于某种原因而阻塞在那里。
注意所有 System.out.println("");行用于调试。
【问题讨论】:
-
定义“不起作用”。您实际看到了哪些意外行为,或者您没有看到哪些预期行为?
-
我不知道这是否与你的问题有关,但 Object.wait 的第一条规则是它必须始终在基于条件的循环中执行,如described in the documentation。跨度>
-
@John Bollinger 就像我说的那样,它似乎在阻塞或什么的。当我希望它打印出 sout 语句的内容,然后继续执行其余代码时,它什么也不做。
-
正如@VGR 所说,
Object.wait()通常应该在循环中执行,因为可能会有虚假唤醒。因此,在从wait()返回后,一个测试一个正在等待的条件是否真的变为真,否则再次等待。 -
每个块中有两个
notify()s 有点可疑,但我们没有足够的代码来判断它是否错误。
标签: java multithreading concurrency synchronization synchronized