你能描述一下在多线程环境下,下面的代码工作不正确吗?我从https://www.javacodegeeks.com/2014/11/multithreading-concurrency-interview-questions-answers.html获取了代码。说明说2个线程可能会一个接一个地进入第二个同步块。这怎么会发生?有两个同步块是什么关系?2个线程如何能够同时访问同步块?
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;
}