wood burning stoves 2.0*
The moose likes Threads and Synchronization and the fly likes wait() vs sleep() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "wait() vs sleep()" Watch "wait() vs sleep()" New topic
Author

wait() vs sleep()

kittu karan
Ranch Hand

Joined: Mar 09, 2008
Posts: 63
Hi,
what is the difference between wait() and sleep() in threads.
Nitesh Kant
Bartender

Joined: Feb 25, 2007
Posts: 1638

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.


apigee, a better way to API!
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
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.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Nitesh Kant
Bartender

Joined: Feb 25, 2007
Posts: 1638

Peter:
I would advise against using the word "exactly" when talking about threading in Java, or any non-realtime system.


Oops, good catch Peter.
 
GeeCON Prague 2014
 
subject: wait() vs sleep()