Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use wait instead of sleep? [duplicate]

I came across a question in which the poster tried to have a thread wait for a second. They were using wait, but outside a synchronized block, and therefore it crashed.

Given a running thread, to pause the execution for a given time, one would do:

Thread.sleep(1000);

This should work as well, and have very similar result:

synchronized(this) {
    this.wait(1000);
}

Using the wait timeout, the thread will unpause 1 second later.

The question is this: if I don't have any monitoring and notifying issue, is there an actual reason to use one over the other?

like image 761
njzk2 Avatar asked Apr 02 '14 22:04

njzk2


1 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.

like image 140
Andrew Lygin Avatar answered Nov 15 '22 11:11

Andrew Lygin