-4

In java we call Thread.sleep(10000) to interrupt a thread , and if we call wait then until we call notify() the Thread sleeps.But recently i went through an article which says we can pass parameter into wait().So if we can pass it and make it wait for the scheduled time , then what is the difference between Thread.sleep(1000) and connections.wait(3000).Below is the link i have went through

https://www.javamex.com/tutorials/synchronization_wait_notify_2.shtml 

Can anyone please explain this situation ? I am really confused.

Mandrek
  • 1,159
  • 6
  • 25
  • 55
  • Thread.sleep does not interrupt the thread... otherwise `InterruptedException` will always be thrown – shinjw Aug 17 '18 at 05:18
  • *we call Thread.sleep(10000) to interrupt a thread* - more study required I think – Scary Wombat Aug 17 '18 at 05:19
  • [`Object#wait(long)`](https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#wait(long)) provides a means to "timeout" after a specified period of time, so it won't "wait" forever to be notified – MadProgrammer Aug 17 '18 at 05:20
  • 1
    *"then what is the difference between Thread.sleep(1000) and connections.wait(3000)"* - you can't "unblock" `sleep` without `interrupting` the thread. `wait(long)` will "wait" to be "notified" for as long as the specified time before continuing – MadProgrammer Aug 17 '18 at 05:22
  • @MadProgrammer but then how does its behavior differs from sleep() , sleep() also will start to after after a certain period – Mandrek Aug 17 '18 at 05:22
  • 1
    @Mandrek It's in "how" it can be "stopped" from waiting. `wait` can be "notified" to continue, this does not affect the `interrupted` state of the thread. The only way to stop `Thread.sleep` early is to interrupt the thread - but then what does that actually mean - theres also synchronisation around the locks for `wait`/`notify` which can provide access to shared/restricted values – MadProgrammer Aug 17 '18 at 05:24

1 Answers1

1

In wait you have to wake up thread using notify, whereas sleep cannot be woken up. Also, wait() is a non-static function and sleep is a static function.

I would highly recommend you to read:

https://javarevisited.blogspot.com/2011/12/difference-between-wait-sleep-yield.html

and Difference between wait() and sleep().

they both explain the differences between wait() and sleep() in a well-versed way making it very smooth to understand.

just coding
  • 173
  • 13