Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Thinking in Java
Prev Contents / Index Next

Sleeping

Another way you can control the behavior of your threads is by calling sleep( ) to cease execution for a given number of milliseconds. In the preceding example, if you replace the call to yield( ) with a call to sleep( ), you get the following:

//: c13:SleepingThread.java
// Calling sleep() to wait for awhile.
import com.bruceeckel.simpletest.*;

public class SleepingThread extends Thread {
  private static Test monitor = new Test();
  private int countDown = 5;
  private static int threadCount = 0;
  public SleepingThread() {
    super("" + ++threadCount);
    start();
  }
  public String toString() {
    return "#" + getName() + ": " + countDown;
  }
  public void run() {
    while(true) {
      System.out.println(this);
      if(--countDown == 0) return;
      try {
        sleep(100);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }
  }
  public static void
  main(String[] args) throws InterruptedException {
    for(int i = 0; i < 5; i++)
      new SleepingThread().join();
    monitor.expect(new String[] {
      "#1: 5",
      "#1: 4",
      "#1: 3",
      "#1: 2",
      "#1: 1",
      "#2: 5",
      "#2: 4",
      "#2: 3",
      "#2: 2",
      "#2: 1",
      "#3: 5",
      "#3: 4",
      "#3: 3",
      "#3: 2",
      "#3: 1",
      "#4: 5",
      "#4: 4",
      "#4: 3",
      "#4: 2",
      "#4: 1",
      "#5: 5",
      "#5: 4",
      "#5: 3",
      "#5: 2",
      "#5: 1"
    });
  }
} ///:~


When you call sleep( ), it must be placed inside a try block because it’s possible for sleep( ) to be interrupted before it times out. This happens if someone else has a reference to the thread and they call interrupt( ) on the thread (interrupt( ) also affects the thread if wait( ) or join( ) has been called for it, so those calls must be in a similar try block—you’ll learn about those methods later). Usually, if you’re going to break out of a suspended thread using interrupt( ) you will use wait( ) rather than sleep( ), so that ending up inside the catch clause is unlikely. Here, we follow the maxim “don’t catch an exception unless you know what to do with it” by re-throwing it as a RuntimeException.

You’ll notice that the output is deterministic—each thread counts down before the next one starts. This is because join( ) (which you’ll learn about shortly) is used on each thread, so that main( ) waits for the thread to complete before continuing. If you did not use join( ), you’d see that the threads tend to run in any order, which means that sleep( ) is also not a way for you to control the order of thread execution. It just stops the execution of the thread for awhile. The only guarantee that you have is that the thread will sleep at least 100 milliseconds, but it may take longer before the thread resumes execution, because the thread scheduler still has to get back to it after the sleep interval expires.

If you must control the order of execution of threads, your best bet is not to use threads at all, but instead to write your own cooperative routines that hand control to each other in a specified order.
Thinking in Java
Prev Contents / Index Next


 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire