Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 713
Murilo Avatar asked Jun 09 '14 17:06

Murilo


2 Answers

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.

like image 191
Rudi Kershaw Avatar answered Nov 08 '22 02:11

Rudi Kershaw


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.

like image 42
Lorenzo Boccaccia Avatar answered Nov 08 '22 02:11

Lorenzo Boccaccia