Multithreading 19.3 Printing odd and even numbers


#1

Hello,

For the problem 19.3 Implement synchronization for the interleaving threads. I am confused on the following part:

public synchronized void waitTurn(boolean oldTurn) {
while (turn != oldTurn) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException in wait(): " + e);
}
}
}

public synchronized void toggleTurn(){
turn ^= true;
notify();
}

in my understanding, both methods share the same LOCK of instance. So if one hold the LOCK, the other method could not run. However, in the following code,
public void run() {
for (int i=1; i<=100; i+=2) {
monitor.waitTurn(SynchronizedThreadMonitor.ODD_TURN);
System.out.println("i= " + i);
monitor.toggleTurn();
}
}

Both Odd and Even thread call the above code. IF even thread first run waitTurn method and wait for the turn change, it holds the LOCK, the odd thread could NOT enter the toggleTurn method and set the turn, it will be a deadlock. But it did not happen. I don’t understand the workflow.

Could you please help me out? Thanks