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?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Junchen Liu
  • 5,435
  • 10
  • 51
  • 62

4 Answers4

11

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
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.

Ofek Ron
  • 8,354
  • 13
  • 55
  • 103
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.

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
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.

Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92