Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What's the difference between the methods sleep() and wait()

 
Qunfeng Wang
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question: What's the difference between the methods sleep() and wait()

Answer: The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

Is that right? A sleep thread can be interrupted by another thread too. I'm a little confused about: sleep/interrupt vs. wait/notify
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another important difference is that wait gives up the monitor on the object (which is in fact why you need to call it on an object).

The uses are totally different. You will use sleep when you just want the current thread to sleep for some time. You use wait when you want the thread to wait for an event in another thread, that is signaled via notify/notifyAll.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic