Murilo
Murilo

Reputation: 4553

What happens with the thread that calls notify

When a thread calls wait() it is blocked and waits for some notify.

But I want to know what happens with a thread that calls notify(). The current thread is blocked, and returns its execution at the notify point ?

Upvotes: 9

Views: 4376

Answers (3)

Lorenzo Boccaccia
Lorenzo Boccaccia

Reputation: 6151

Notify doesn't put current thread to sleep, only wakes up other threads that have waited on the same mutex

Notify doesn't block the executing thread and both the notifier and the waiter happily execute concurrently after that. Notify notifies one of the waiters at random, if you have more than one thread waiting and you want to wake them all you need to use notifyAll. Note that as all thread will still be in a critical section they will be marked active but will exit the critical block one at a time.

Notify doesn't block even if there are no waiting threads.

Note that this only represent the state of the thread: both threads will be active but actual dispatching of instruction depends: if you have more thread than cpu one of them will wait for its timeslice on the cpu.

Upvotes: 3

m.abhinav
m.abhinav

Reputation: 21

  • wait() tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).
  • notify() wakes up the first thread that called wait() on the same object.

Under ideal condition notify() is called when thread completes its execution to go back again to calling thread. But if used before completion then the thread will continue its normal execution until reaches natural end.

Upvotes: 1

Rudi Kershaw
Rudi Kershaw

Reputation: 13022

Nothing happens to the current thread that calls notify(), it continues to run until it's natural end.

The wait() and notify() methods must be called within a synchronized context. As soon as the synchronized block that contains the notify() call finishes, the lock is then available and the block containing the wait() call in another thread can then continue.

Calling notify simply moves the waiting thread back into the runnable thread pool. That thread can then continue as soon as the lock is available.

Upvotes: 12

Related Questions