我正在从互联网上阅读一些东西。这是关于下面代码的问题。以下从某个队列实现中检索整数值的代码是否正确?答案是这样的:
尽管上面的代码使用队列作为对象监视器,但它在多线程环境中的行为并不正确。这样做的原因是它有两个独立的同步块。当两个线程在第 6 行被另一个调用 notifyAll() 的线程唤醒时,两个线程一个接一个地进入第二个同步块。在第二个块中,队列现在只有一个新值,因此第二个线程将轮询一个空队列并获取 null 作为返回值。
我在想同步块会阻止不同的线程同时访问这个资源,不是吗?谢谢你。
public Integer getNextInt() {
Integer retVal = null;
synchronized (queue) {
try {
while (queue.isEmpty()) {
queue.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (queue) {
retVal = queue.poll();
if (retVal == null) {
System.err.println("retVal is null");
throw new IllegalStateException();
}
}
return retVal;
}