2

Both are trying to do the similar thing, which is make some effect on thread.

I know that thread.sleep is to let the CURRENT thread to sleep and wait can let any thread to wait, if they are trying to get the object's lock.

The question is, most of the time they are doing the similar thing - what makes you choose one over another?

0

4 Answers 4

12

No, Object.wait() will only ever cause the current thread to block, too.

The main difference is that sleep() instructs the current thread to sleep for a period of time, whereas wait() instructs the current thread to release a monitor, then sleep until the monitor is notified. In other words, wait() is a coordination primitive between threads, whereas sleep() only cares about the passage of time (assuming no interruptions).

Sign up to request clarification or add additional context in comments.

Comments

1

Sleep and Wait looks deciving, They differ by a lot :

Sleep - makes the Thread sleep for a given amount of time - good for Schedualing tasks, Animations and more...

Wait - mostly used without limit of time, makes one thread Wait for something to heppen, this is the best practice for synchronization.

if youre trying to Implement Wait by using Sleep, thats bad practice, which somewhat close to some very bad thing called Busy Waiting.

Comments

0

One is used to synchronize Threads together while the other one is used to sleep for a given amount of time.

If you want to synchronize Threads together, user wait/notify. If you want to sleep for a known amount of time, use Thread.sleep.

Comments

0

These two methods do very different things: Thread.sleep waits a specified amount of time while Object.wait waits for a notify event (which may take arbitrary amount of time to happen).

Both can only put the current thread to sleep. Also, Object.wait requires that the current thread is holding the monitor associated with the object.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.