MultiThreaded Programming  «Prev  Next»

Lesson 6Sleeping threads
Objective Put threads to sleep.

Sleeping Threads in Java

When you call the start() method on a thread, the thread's run() method is executed.
The thread will continue to run as long as its run() method is executing.
It is possible to temporarily pause a thread, which is known as putting a thread to sleep. Threads are put to sleep for a specified amount time, after which they awaken and resume execution where they left off.
Since you specify exactly how long a thread is to sleep, sleeping threads can be used as a timing mechanism. For example, you might want to change the images in an animation at regularly timed intervals.
To put a thread to sleep, you call the sleep() method and pass in the number of milliseconds for it to sleep. To perform a timed repetitive operation such as updating an animation image, you put the thread to sleep from within a while loop in the run() method:

public void run() {
  while (Thread.currentThread() == thread) {
    // Repetitive code goes here
    // Wait for one second
    try {
      Thread.sleep(1000);
    }
    catch (InterruptedException e) {
      break;
    }
  }
} 

This example will repeat any code above the sleep code every second, as specified by the 1000 millisecond parameter to the sleep() method. You could increment an image counter and repaint an applet window in this code to establish an animation that updates its image every second.
The currentThread() method is called to ensure that the while loop only executes while the current thread is active. In this case there is only one thread so the while loop is effectively an infinite loop.
You will learn about the try-catch exception[1] handling code in the next module.
An example of an exception is attempting to divide a number by zero or the system running out of memory.
In the next lesson, you will examine thread synchronization and how it impacts multithreaded programming.

Modify Slide Show - Exercise

Click the Exercise link below to automate the SlideShow applet.
Modify Slide Show - Exercise

[1]Exception: An exceptional situation that a program does not know how to handle is known as an exception.