Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why are notify() & notifyAll() are in Object class??where aswe call from Thread class

 
Shridhar. Blr.
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
Can anyone explain me :
why are notify() and notifyAll() methods are in Object class?? where as these methods are called on Thread Class instance..
I think these methods should be part of Thread Class..
Thanks in Advance..
~Shridhar..
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
wait() notify(), and notifyAll() are very rarely, if ever, called on a java.lang.Thread.
Every Java object contains a lock (also called a "mutex"). When you call a synchronized method, the Thread that calls that method must "grab" the lock for the object the method is called on. This can only happen if no other Thread already holds the lock. While a Thread holds the lock on an object, no other Thread can enter a other synchronized method on that same object.
There are only two ways that a Thread that holds a lock can release it: either the synchronized method returns, or the Thread calls wait() on the locked object. The wait() method releases the lock and goes to sleep. Another thread can then acquire the lock.
wait() doesn't return from its sleep until two things happen: first, some other thread, which must hold the lock on that same object, must call notify() or notifyAll() on that locked object. Secondly, this other Thread must release the lock.
OK, so, as you see, wait, notify and notiftAll are used to manipulate the locks of individual objects. Since an object of any class can have synchronized methods and be used as a lock, these methods are in Object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic