Both sleep() and wait() are used to hold the current thread, but they were designed for different use cases:
sleep() usually used when you know exactly how long you want your thread to be inactive. After a specified timeout, it will automatically wake up, without external interference. There is still a chance that someone decides to wake up your topic earlier if something urgent happens (in this case, the sleep() call will end with an InterruptedException ). For example, the user decided to close the application when the thread was sleeping, or something like this.
So, sleep() is like setting an alarm to wake you up in an hour while you were dozing. But someone may wake you up earlier to say that the building is on fire, and it is better to get up and do something about it.
wait() , on the other hand, is designed to hold the thread until something happens in the future. You do not know how long it will take. There must be someone outside who will wake the thread by calling notify() or notifyAll() on the monitor (on the same object that was used to call wait() ). For example, a thread has delegated some work to another thread and wants to sleep until the work is completed. You also have the option of limiting the wait time, but the thread will not continue executing until it can re-capture the monitor. The waiting thread can still be interrupted just like with sleep() .
So, wait() like you have a single screwdriver in the workshop, give it to your colleague for a while and decide to come around a bit until he or she finishes. You ask them to wake you when your screwdriver is free again, and you can continue your work. You can also set the alarm as in sleep() , but you cannot return to work until you return the screwdriver.
Of course, these are the usual simple approaches to using methods. You can develop your own usage scenarios based on their functionality.
Andrew Lygin
source share