I have not worked in multithreading
, what is the difference between join and wait ,notify method ? is the difference only limited to obtain lock
and refrain other threads
from accessing it or are there other use cases?
Why should I go for wait
and notify
in multithreading
when join
can be used for completion of thread
execution?
It would be helpful if any real time examples have been provided
The method join
(of class Thread
) wait for a thread to die:
Waits for this thread to die.
The methods wait
, notify
, notifyAll
are not related to the end of execution of one thread.
The method wait
:
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait()
Methods notify
and notifyAll
are used to awake a sleeping thread:
Wakes up a single thread that is waiting on this object's monitor.
A common use of wait
with notify
is accessing a shared resource.
When the resource is not available the consumer wait on the monitor.
When the producer create the resource it notify (or notifyAll) to awake thread (or threads) waiting for this resource.
A common use of join is blocking the main thread until a configuration thread has finished his activity before continuing.
join(
): Waits for this thread to die.
The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,
t.join();
causes the current thread to pause execution until t's thread terminates.
wait()
: Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
notify()
: Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened.
notifyAll()
:Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.
Refer to below posts for more details.
Difference between wait() and sleep()
Difference between Synchronized block with wait/notify and without them?
Examples:
A simple scenario using wait() and notify() in java
work-with-wait-notify-and-notifyall
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With