You're waiting and notifying different objects (monitors).
The idea is that you can call obj.wait()
to wait for someone to do obj.notify()
, while you're doing objA.wait()
and objB.notify()
.
Change your printOdd
method to something like
private void printOdd(int i) {
synchronized (lock) { // <-------
while (!oddTurn) {
try {
lock.wait(); // <-------
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(type + i);
oddTurn = false;
lock.notifyAll(); // <-------
}
}
and the printEven
method similarly.
Then provide the NumberPrinter
with a lock
object:
Object lock = new Object();
Thread odd = new Thread(new NumberPrinter("odd", lock));
Thread even = new Thread(new NumberPrinter("even", lock));
Output:
odd1
even2
odd3
even4
odd5
even6
odd7
even8
odd9
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…