- Every Object has a monitor, acquiring that monitors allow thread to hold lock on object. But Thread class does not have any monitors.
- wait(), notify() and notifyAll() are called on objects only > When wait() method is called on object by thread it waits for another thread on that object to release object monitor by calling notify() or notifyAll() method on that object.
When notify() method is called on object by thread it notifies all the threads which are waiting for that object monitor that object monitor is available now.
So, this shows that wait(), notify() and notifyAll() are called on objects only.
- Wait(), notify() and notifyAll() method being in Object class allows all the threads created on that object to communicate with other. [As multiple threads may exist on same object].
- As multiple threads exists on same object. Only one thread can hold object monitor at a time. As a result thread can notify other threads of same object that lock is available now. But, thread having these methods does not make any sense because multiple threads exists on object it's not other way around (i.e. multiple objects exists on thread).
- Now let’s discuss one hypothetical scenario, what will happen if Thread class contains wait(), notify() and notifyAll() methods?
Having wait(), notify() and notifyAll() methods means Thread class also must have their monitor.
Every thread having their monitor will create few problems -
>Thread communication problem.
>Synchronization on object won’t be possible- Because object has monitor, one object can have multiple threads and thread hold lock on object by holding object monitor. But if each thread will have monitor, we won’t have any way of achieving synchronization.
>Inconsistency in state of object (because synchronization won't be possible).
/** JavaMadeSoEasy.com */
RELATED LINKS>
Volatile keyword vs synchronized>
Volatile keyword in java- difference between synchronized and volatile, 10 key points about volatile keyword, why volatile variables are not cached in memory
Differences between synchronized and volatile keyword in detail
Race Condition >
Race condition in multithreading and it's solution
Important Thread methods (salient features, usage with programs)>
Join() method - ensure all threads that started from main must end in order in which they started and also main should end in last. Types of join() method-10 salient features of join
Sleep() method in threads - 10 key features with programs
Yield() method in threads - 8 key features with programs
Wait() and notify() methods- Definition, 8 key features, solving consumer producer problem with & without these methods and consequences of not using wait() and notify() methods.
Daemon threads - 12 salient features of Daemon Thread
2 alternate ways to stop thread, as stop() method is deprecated
Using Suspend and resume method in threads
Differences between important thread methods >