What is the difference between sleep and wait



The first explanation: the

functions are similar, and they are all used for thread control. The biggest essential difference between them is: sleep() does not release synchronization locks, and wait() releases synchronization contractions. 
  
  The difference in usage is: sleep(milliseconds) You can use the time specification to wake him up automatically. If the time is not enough, you can only call interrupt() to forcibly interrupt; wait() can be awakened directly with notify().

The second explanation:

sleep is a static method of the Thread class . The function of sleep is to let the thread sleep for the specified time and resume when the time arrives, that is to say, sleep will resume the thread execution when the time arrives event, for example:
try{
System.out.println("I'm going to bed ");
Thread.sleep(1000);
System.out.println("I wake up");
}
catch(IntrruptedException e) {
}
wait is the method of Object, which means that you can call the wait method on any object, and call The wait method will suspend the caller's thread until another thread calls the notify method of the same object to reactivate the caller, for example:
//Thread 1

try{
obj.wait();//suspend thread until obj. notify() is called
}
catch(InterrputedException e) {
}



Object class provides wait(), notify() and notifyAll() methods to operate thread sleep() can put a thread to sleep, and the parameter can specify a time. And wait() can suspend a thread until it times out or the thread is woken up.     wait has two forms wait() and wait(milliseconds).


















The differences between sleep and wait are:
  1. These two methods come from different classes, Thread and Object
  . 2. The most important thing is that the sleep method does not release the lock, while the wait method releases the lock, so that other threads can use the synchronization control block or method. .
  3, wait, notify and notifyAll can only be used in synchronization control methods or synchronization control blocks, while sleep can be used
    anywhere
   synchronized(x){
      x.notify()
     //or wait()
   }
   4, sleep must catch exceptions , while wait, notify and notifyAll do not need to catch exceptions

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326901850&siteId=291194637