Java Glossary : sleep

CMP home Java glossary home Menu no menu Last updated 2004-06-28 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You are here : home : Java Glossary : S words : sleep.

sleep
You can put a thread to sleep for n milliseconds with code like this:

try
   {
   // Sleep at least n milliseconds.
   // 1 millisecond = 1/1000 of a second.
   Thread.sleep( n );
   }
catch ( InterruptedException e )
   {
   System.out.println( "awakened prematurely" );

   // if you want to simulate the interrupt happening
   // just after awakening, use the following line
   // so that our next sleep or wait
   // will be interrupted immediately.
   // Thread.currentThread().interrupt();
   }

This guarantees to sleep for at least n milliseconds; like Sleeping Beauty, it may sleep for considerably more if the system is busy. If the Thread awakens normally after its sleep, there will be no InterruptedException, but if some other Thread awakens it prematurely with Thread.Interrupt there will be an InterruptedException.

You might try to remove the catch and wonder why the compiler complains. Java wants to prepare for the possibility that the sleep may be prematurely awakened by some wandering Prince Charming. It is not nearly as sure as you are that it can't happen.

You can even put main event-processing thread to sleep, but if you do, no events will be processed; buttons will be dead.

You don't need to implement Runnable to use sleep.

It is best to use wait/notify to co-ordinate threads, not have them sleep and wake up and check then sleep again. There is no guarantee Threads won't sleep longer than you requested.

See the warning under Gotchas:Threads on why a sleeping task may never waken if somebody fiddles with the system clock setting while your thread is asleep.


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 11204.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/sleep.html J:\mindprod\jgloss\sleep.html