Why does the Object
class have thread-related methods, like wait()
, notify()
, notifyAll()
?
We need to extend Thread
or implement Runnable
to give Thread-like behavior to a class. So why weren't they made part of any Thread
or Runnable
object?
If wait() and notify() were on the Thread instead then each thread would have to know the status of every other thread and there is no way to know thread1 that thread2 was waiting for any resource to access. Hence, notify, wait, notifyAll methods are defined in object class in Java.
All these people don't know who is waiting for these they acquire and release resource. It is resources announces that they are free and available, not the people , this is why object class has wait() and notify() methods.
There are five of these methods: public final void notify() public final void notifyAll() public final void wait()
Java concurrency model uses locks to implement mutually exclusive access to objects in a multi-threaded environment and locks are associated with every object in Java (of type 'Object'), not only with Threads.
1) Wait and notify are communication mechanism between two threads in Java. And Object
class is correct place to make them available for every object as it is the superclass of all Objects.
2) Locks are made available on per Object basis, which is another reason wait and notify is declared in Object class rather then Thread class.
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