dgl*_*glo 6 java multithreading thread-safety
我有一个Java线程做这样的事情:
while (running) {
synchronized (lock) {
if (nextVal == null) {
try {
lock.wait();
} catch (InterruptedException ie) {
continue;
}
}
val = nextVal;
nextVal = null;
}
...do stuff with 'val'...
}
Run Code Online (Sandbox Code Playgroud)
在其他地方我设置这样的值:
if (val == null) {
LOG.error("null value");
} else {
synchronized (lock) {
nextVal = newVal;
lock.notify();
}
}
Run Code Online (Sandbox Code Playgroud)
偶尔(实际上每两千万次)nextVal将被设置为null.我已经抛出了记录消息,我可以看到执行顺序如下:
我已经明确检查过锁定第二次醒来,它没有被打断.
我在这里做错了吗?
是的,Thread我自然醒了。Javadoc中明确说明了这一点:
“线程也可以在没有被通知、中断或超时的情况下唤醒,即所谓的虚假唤醒。”
你需要wait循环。javadoc中也明确提到了这一点:
synchronized (obj) {
while (<condition does not hold>)
obj.wait(timeout);
... // Perform action appropriate to condition
}
Run Code Online (Sandbox Code Playgroud)
在你的情况下:
while (running) {
synchronized (lock) {
while (nextVal == null) {
try {
lock.wait();
} catch (InterruptedException ie) {
//oh well
}
}
val = nextVal;
nextVal = null;
}
...do stuff with 'val'...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
883 次 |
| 最近记录: |