File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

wait() vs sleep()

 
kittu karan
Ranch Hand
Posts: 63
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
what is the difference between wait() and sleep() in threads.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
googling on "java threads difference wait sleep" will give you a whole lot of results. Those links will tell you the differences between the methods technically.

In simple and non-technical terms, Consider the following 2 cases:

Case 1: You have a bus to catch that is guaranteed to come at 8:00 am.
Case 2: You have a bus to catch but you do not know the timing. However, you live next to the bus station and your travel agent will call you as soon as the bus comes.

In case 1, you can sleep without any worries till 7:00 am (assuming you take an hour to reach the bus stand.)

In case 2, you need to wait for the travel agent's call but you can still suspend all your work and relax. As an addition, you may wish to wait only till 6:00 am. If the travel agent does not call you will go to the bus stand and catch some other bus.

Making an anolgy of the above situation with threads,
Wait is the condition of a thread that is waiting for some other thread to notify it when the appropriate time comes. This also can be a timed wait. (You will wait only till 6 for the travel agent call.)
On the other hand, sleep is the condition of a thread that knows that the appropriate time will come after exactly "n" milliseconds.
 
Peter Chase
Ranch Hand
Posts: 1970
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Nitesh Kant:
exactly "n" milliseconds.


I would advise against using the word "exactly" when talking about threading in Java, or any non-realtime system. The amount of time that passes in sleep(N) will usually be approximately N milliseconds, but could be significantly more if the system has lots else to do.

Additionally, the resolution of the clock on some systems is not as good as 1 millisecond. For instance, on Windows, it's often 15 milliseconds, so sleep(1) and sleep(15) are pretty much the same.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Peter:
I would advise against using the word "exactly" when talking about threading in Java, or any non-realtime system.


Oops, good catch Peter.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic