Can I use wait instead of sleep?

This question already has an answer here:

  • Difference between wait() and sleep() 33 answers

  • Both sleep() and wait() are used to put the current thread on hold, but they were designed for different use cases:

    sleep() is usually used when you know exactly how long you want your thread to be inactive. After the given timeout, it will wake up automatically, without interference from outside. There's still a chance that someone will decide to wake up your thread earlier if something urgent happens (in this case, the call to sleep() will end up with an InterruptedException ). For instance, the user has decided to close the application when the thread was asleep, or something like this.

    So, sleep() is like setting an alarm clock to wake you up in an hour while going to doze. But someone can wake you up earlier to say that the building is on fire and it's better to get up and do something about it.

    wait() , on the other hand, is designed to put a thread on hold until something happens sometime in the future. You don't know how long it will take. There must be someone outside who will wake up the thread by calling notify() or notifyAll() on the monitor (on the same object that was used to call wait() ). For instance, a thread has delegated some job to another thread and wants to sleep until the job is done. You also have an option to limit the waiting time, but the thread won't continue execution until it can reacquire the monitor. The waiting thread is still can be interrupted the same way as with the sleep() .

    So, wait() is like you have the only screwdriver in the workshop, lend it to your coworker for a while and decide to doze a bit until he or she has finished. You ask them to wake you up when your screwdriver is free again and you can continue your job. You can also set an alarm clock like in sleep() , but you won't be able to get back to work until you get your screwdriver back.

    Of course, those are just usual simple approaches to using the methods. You can devise your own usage scenarios based on their functionality.


    The difference is pretty clear in the javadoc:

    void Object.wait() : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

    void Object.wait(long timeout) : Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

    static void Thread.sleep(long millis) : Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

    Otherwise, the question is asked and got an explained answer here .

    链接地址: http://www.djcxy.com/p/92136.html

    上一篇: 睡眠()和等待()之间的混淆

    下一篇: 我可以用等待而不是睡觉吗?