To do obj.wait()
and obj.notify()
, you need to own the monitor of the object you're going to wait/notify on. In your code, you probably don't want thread1.notify(). Example:
Object someSharedObject = ...
Thread1:
synchronized(someSharedObject) {
// while NOT if for spurious wake ups.
while(!conditionFullfiled) someSharedObject.wait();
}
Thread2:
synchronized(someSharedObject) {
if(conditionFullfiled) someSharedObject.notify(); // this wakes thread1
}
The synchronized
lock is on someSharedObject
(can be this
), which means the two threads will never clash. .wait()
releases the currently held monitor, so Thread2 will not be blocked when Thread1 is waiting.
Edit: I learnt something about spurious wake ups. The .wait()
must be done in a while
loop - if
is not enough. Why do threads spontaneously awake from wait()? . Thanks Enno Shioji for teaching me.
Edit: Clarified .wait()
releases monitor.