你能描述一下在多線程環境下,下面的代碼工作不正確嗎?我從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;
}