Communiquez avec les autres et partagez vos connaissances professionnelles

Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.

Suivre

In Java why wait() and notify() methods are in Object class but used in thread?

In java why wait() and notify() method are present in object class but used in Thread?

user-image
Question ajoutée par Zishan Khan , Sr software engineer , niit technology
Date de publication: 2017/12/22
Utilisateur supprimé
par Utilisateur supprimé

wait()=

If threads calls wait() on any object it immeditaly release the lock of the particular object and entered in to waiting state .

notify()=

If threads calls notify() on any object it  release the lock of the particular object butmay not immeditaly .

 

Utilisateur supprimé
par Utilisateur supprimé

wait

Object wait methods has three variance, one which waits indefinitely for any other thread to call notify or notifyAll method on the object to wake up the current thread. Other two variances puts the current thread in wait for specific amount of time before they wake up.

 

notify

notify method wakes up only one thread waiting on the object and that thread starts execution. So if there are multiple threads waiting for an object, this method will wake up only one of them. The choice of the thread to wake depends on the OS implementation of thread management.

Anupama Patil
par Anupama Patil , GIS Associate , Wipro LTD

These methods are communication mechanism between two threads in java. object class is the correct place to make them available for every object. and locks are made available ob per object basis. and these () works on locks,and locks are in object.

Every object in java has only one lock(monitor) and wait(),notify(),notifyAll() are used for monitor sharing thats why they are part of object class rather than Thread class. These methods works on the locks and locks are associated with Object and not Threads

Ahmed Salem
par Ahmed Salem , Senior Software Developer , Silicon Egypt Technologies

Because Locks are made available on per Object basis, which is another reason wait and notify is declared in Object class rather then Thread class.

 

Utilisateur supprimé
par Utilisateur supprimé

wait means it's having some time to wait.exceptions used in java.that is very big concept in java.checked exception and unchecked execption.wait is checketed exception and thread is unchecked execpetion.

More Questions Like This