Sleep

Sometimes the computer may run too fast for the human beings. If this is the case you need to slow it down. You can make a particular Thread slow down by interspersing it with calls to the Thread.sleep(ms) method. ms is the number of milliseconds you want the thread to wait before proceeding on. There are one thousand milliseconds in a second.

Another thread can invoke a sleeping thread's interrupt() method. If this happens, the sleep() method throws an InterruptedException. Therefore when you put a thread to sleep, you need to catch InterruptedExceptions. Thus every call to sleep() should be wrapped in a try catch block like this:

try {
  Thread.sleep(1000);
}
catch (InterruptedException ex) {
    
}

To delay a program for a fixed amount of time you often do something like this:

try {
  Thread.sleep(1000);
}
catch (InterruptedException ex) {
    
}

Previous | Next | Top | Cafe au Lait

Copyright 2006 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified April 28, 2006