Home > Back-end >  The difference between wait () and sleep ()
The difference between wait () and sleep ()

Time:01-28

1: from different class
The wait () from the Object class, sleep () from the Thread class

The release of 2 about lock
Wait () will release the lock, the sleep () won't lock is released, can be understood as holding the lock sleep

3 use different
==sleep () can be used in any place, wait () can only be used in the synchronized code block==

4 if you need to catch exceptions
Wait () does not need to catch exceptions
Sleep () must be an exception

CodePudding user response:

The wait (), notify () and notifyAll ();
Collocation is used, the wait () is to obtain using compulsory object to head the Monitor is the case, so the wait () often appear together with synchronized,

Wait is object to provide method, which is so clear in multithreaded programming object in the wait (), the object should be and synchronized objects are the same,

Sleep () thread is suspended and will not release the lock, but it will release the computing resources, CPU usage to print out a classic before the sine function is through the sleep () implementation,

Wait and sleep improper use will have corresponding anomaly,

Study suggested that Java objects
  • Related