Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Basic threads

The simplest way to create a thread is to inherit from java.lang.Thread, which has all the wiring necessary to create and run threads. The most important method for Thread is run( ), which you must override to make the thread do your bidding. Thus, run( ) is the code that will be executed "simultaneously" with the other threads in a program.

The following example creates five threads, each with a unique identification number generated with a static variable. The Thread's run( ) method is overridden to count down each time it passes through its loop and to return when the count is zero (at the point when run( ) returns, the thread is terminated by the threading mechanism).

//: c13:SimpleThread.java
// Very simple Threading example.
import com.bruceeckel.simpletest.*;
  public class SimpleThread extends Thread {
  private static Test monitor = new Test();
  private int countDown = 5;
  private static int threadCount = 0;
  public SimpleThread() {
   super("" + ++threadCount); // Store the thread name
   start();
  }
  public String toString() {
   return "#" + getName() + ": " + countDown;
  }
  public void run() {
    while(true) {
     System.out.println(this);
     if(--countDown == 0) return;
   }
  }
  public static void main(String[] args) {
   for(int i = 0; i < 5; i++)
     new SimpleThread();
   monitor.expect(new String[] {
     "#1: 5",
     "#2: 5",
     "#3: 5",
     "#5: 5",
     "#1: 4",
     "#4: 5",
     "#2: 4",
     "#3: 4",
     "#5: 4",
     "#1: 3",
     "#4: 4",
     "#2: 3",
     "#3: 3",
     "#5: 3",
     "#1: 2",
     "#4: 3",
     "#2: 2",
     "#3: 2",
     "#5: 2",
     "#1: 1",
     "#4: 2",
     "#2: 1",
     "#3: 1",
     "#5: 1",
     "#4: 1"
   }, Test.IGNORE_ORDER + Test.WAIT);
  }
} ///:~

The thread objects are given specific names by calling the appropriate Thread constructor. This name is retrieved in toString( ) using getName( ).

A Thread object's run( ) method virtually always has some kind of loop that continues until the thread is no longer necessary, so you must establish the condition on which to break out of this loop (or, as in the preceding program, simply return from run( )). Often, run( ) is cast in the form of an infinite loop, which means that, barring some factor that causes run( ) to terminate, it will continue forever (later in the chapter you'll see how to safely signal a thread to stop).

In main( ) you can see a number of threads being created and run. The start( ) method in the Thread class performs special initialization for the thread and then calls run( ). So the steps are: the constructor is called to build the object, it calls start( ) to configure the thread, and the thread execution mechanism calls run( ). If you don't call start( ) (which you don't have to do in the constructor, as you will see in subsequent examples), the thread will never be started.

The output for one run of this program will be different from that of another, because the thread scheduling mechanism is not deterministic. In fact, you may see dramatic differences in the output of this simple program between one version of the JDK and the next. For example, a previous JDK didn't time-slice very often, so thread 1 might loop to extinction first, then thread 2 would go through all of its loops, etc. This was virtually the same as calling a routine that would do all the loops at once, except that starting up all those threads is more expensive. In JDK 1.4 you get something like the output from SimpleThread.java, which indicates better time-slicing behavior by the scheduler—each thread seems to be getting regular service. Generally, these kinds of JDK behavioral changes have not been mentioned by Sun, so you cannot plan on any consistent threading behavior. The best approach is to be as conservative as possible while writing threading code.

When main( ) creates the Thread objects, it isn't capturing the references for any of them. With an ordinary object, this would make it fair game for garbage collection, but not with a Thread. Each Thread "registers" itself so there is actually a reference to it someplace, and the garbage collector can't clean it up until the thread exits its run( ) and dies.

Yielding

If you know that you've accomplished what you need to in your run( ) method, you can give a hint to the thread scheduling mechanism that you've done enough and that some other thread might as well have the CPU. This hint (and it is a hint—there's no guarantee your implementation will listen to it) takes the form of the yield( ) method.

We can modify the preceding example by yielding after each loop:

//: c13:YieldingThread.java
// Suggesting when to switch threads with yield().
import com.bruceeckel.simpletest.*;

public class YieldingThread extends Thread {
  private static Test monitor = new Test();
  private int countDown = 5;
  private static int threadCount = 0;
  public YieldingThread() {
    super("" + ++threadCount);
    start();
  }
  public String toString() {
    return "#" + getName() + ": " + countDown;
  }
  public void run() {
    while(true) {
      System.out.println(this);
      if(--countDown == 0) return;
      yield();
    }
  }
  public static void main(String[] args) {
    for(int i = 0; i < 5; i++)
    new YieldingThread();
  monitor.expect(new String[] {
      "#1: 5",
      "#2: 5",
      "#4: 5",
      "#5: 5",
      "#3: 5",
      "#1: 4",
      "#2: 4",
      "#4: 4",
      "#5: 4",
      "#3: 4",
      "#1: 3",
      "#2: 3",
      "#4: 3",
      "#5: 3",
      "#3: 3",
      "#1: 2",
      "#2: 2",
      "#4: 2",
      "#5: 2",
      "#3: 2",
      "#1: 1",
      "#2: 1",
      "#4: 1",
      "#5: 1",
      "#3: 1"
    }, Test.IGNORE_ORDER + Test.WAIT);
  }
} ///:~

By using yield( ), the output is evened up quite a bit. But note that if the output string is longer, you will see output that is roughly the same as it was in SimpleThread.java (try it—change toString( ) to put out longer and longer strings to see what happens). Since the scheduling mechanism is preemptive, it decides to interrupt a thread and switch to another whenever it wants, so if I/O (which is executed via the main( ) thread) takes too long, it is interrupted before run( ) has a chance to yield( ). In general, yield( ) is useful only in rare situations, and you can't rely on it to do any serious tuning of your application.

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.

Priority

The priority of a thread tells the scheduler how important this thread is. Although the order that the CPU attends to an existing set of threads is indeterminate, if there are a number of threads blocked and waiting to be run, the scheduler will lean toward the one with the highest priority first. However, this doesn't mean that threads with lower priority aren't run (that is, you can't get deadlocked because of priorities). Lower priority threads just tend to run less often.

Here's SimpleThread.java modified so that the priority levels are demonstrated. The priorities are adjusting by using Thread's setPriority( ) method.

//: c13:SimplePriorities.java
// Shows the use of thread priorities.
import com.bruceeckel.simpletest.*;

public class SimplePriorities extends Thread {
  private static Test monitor = new Test();
  private int countDown = 5;
  private volatile double d = 0; // No optimization
  public SimplePriorities(int priority) {
    setPriority(priority);
    start();
  }
  public String toString() {
    return super.toString() + ": " + countDown;
  }
  public void run() {
    while(true) {
      // An expensive, interruptable operation:
      for(int i = 1; i < 100000; i++)
        d = d + (Math.PI + Math.E) / (double)i;
      System.out.println(this);
      if(--countDown == 0) return;
    }
  }
  public static void main(String[] args) {
    new SimplePriorities(Thread.MAX_PRIORITY);
    for(int i = 0; i < 5; i++)
      new SimplePriorities(Thread.MIN_PRIORITY);
    monitor.expect(new String[] {
      "Thread[Thread-1,10,main]: 5",
      "Thread[Thread-1,10,main]: 4",
      "Thread[Thread-1,10,main]: 3",
      "Thread[Thread-1,10,main]: 2",
      "Thread[Thread-1,10,main]: 1",
      "Thread[Thread-2,1,main]: 5",
      "Thread[Thread-2,1,main]: 4",
      "Thread[Thread-2,1,main]: 3",
      "Thread[Thread-2,1,main]: 2",
      "Thread[Thread-2,1,main]: 1",
      "Thread[Thread-3,1,main]: 5",
      "Thread[Thread-4,1,main]: 5",
      "Thread[Thread-5,1,main]: 5",
      "Thread[Thread-6,1,main]: 5",
      "Thread[Thread-3,1,main]: 4",
      "Thread[Thread-4,1,main]: 4",
      "Thread[Thread-5,1,main]: 4",
      "Thread[Thread-6,1,main]: 4",
      "Thread[Thread-3,1,main]: 3",
      "Thread[Thread-4,1,main]: 3",
      "Thread[Thread-5,1,main]: 3",
      "Thread[Thread-6,1,main]: 3",
      "Thread[Thread-3,1,main]: 2",
      "Thread[Thread-4,1,main]: 2",
      "Thread[Thread-5,1,main]: 2",
      "Thread[Thread-6,1,main]: 2",
      "Thread[Thread-4,1,main]: 1",
      "Thread[Thread-3,1,main]: 1",
      "Thread[Thread-6,1,main]: 1",
      "Thread[Thread-5,1,main]: 1"
    }, Test.IGNORE_ORDER + Test.WAIT);
  }
} ///:~

In this version, toString( ) is overridden to use Thread.toString( ), which prints the thread name (which you can set yourself via the constructor; here it's automatically generated as Thread-1, Thread-2, etc.), the priority level, and the "thread group" that the thread belongs to. Because the threads are self-identifying, there is no threadNumber in this example. The overridden toString( ) also shows the countdown value of the thread.

You can see that the priority level of thread 1 is at the highest level, and all the rest of the threads are at the lowest level.

Inside run( ), 100,000 repetitions of a rather expensive floating-point calculation have been added, involving double addition and division. The variable d has been made volatile to ensure that no optimization is performed. Without this calculation, you don't see the effect of setting the priority levels (try it: comment out the for loop containing the double calculations). With the calculation, you see that thread 1 is given a higher preference by the thread scheduler (at least, this was the behavior on my Windows 2000 machine). Even though printing to the console is also an expensive behavior, you won't see the priority levels that way, because console printing doesn't get interrupted (otherwise, the console display would get garbled during threading), whereas the math calculation can be interrupted. The calculation takes long enough that the thread scheduling mechanism jumps in and changes threads, and pays attention to the priorities so that thread 1 gets preference.

You can also read the priority of an existing thread with getPriority( ) and change it at any time (not just in the constructor, as in SimplePriorities.java) with setPriority( ).

Although the JDK has 10 priority levels, this doesn't map well to many operating systems. For example, Windows 2000 has 7 priority levels that are not fixed, so the mapping is indeterminate (although Sun's Solaris has 231 levels). The only portable approach is to stick to MAX_PRIORITY, NORM_PRIORITY, and MIN_PRIORITY when you're adjusting priority levels.

Daemon threads

A "daemon" thread is one that is supposed to provide a general service in the background as long as the program is running, but is not part of the essence of the program. Thus, when all of the non-daemon threads complete, the program is terminated. Conversely, if there are any non-daemon threads still running, the program doesn't terminate. There is, for instance, a non-daemon thread that runs main( ).

//: c13:SimpleDaemons.java
// Daemon threads don't prevent the program from ending.
  public class SimpleDaemons extends Thread {
  public SimpleDaemons() {
    setDaemon(true); // Must be called before start()
    start();
  }
  public void run() {
    while(true) {
    try {
      sleep(100);
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
    System.out.println(this);
    }
  }
  public static void main(String[] args) {
    for(int i = 0; i < 10; i++)
      new SimpleDaemons();
  }
} ///:~

You must set the thread to be a daemon by calling setDaemon( ) before it is started. In run( ), the thread is put to sleep for a little bit. Once the threads are all started, the program terminates immediately, before any threads can print themselves, because there are no non-daemon threads (other than main( )) holding the program open. Thus, the program terminates without printing any output.

You can find out if a thread is a daemon by calling isDaemon( ). If a thread is a daemon, then any threads it creates will automatically be daemons, as the following example demonstrates:

//: c13:Daemons.java
// Daemon threads spawn other daemon threads.
import java.io.*;
import com.bruceeckel.simpletest.*;

class Daemon extends Thread {
  private Thread[] t = new Thread[10];
  public Daemon() {
    setDaemon(true);
    start();
  }
  public void run() {
    for(int i = 0; i < t.length; i++)
        t[i] = new DaemonSpawn(i);
      for(int i = 0; i < t.length; i++)
        System.out.println("t[" + i + "].isDaemon() = "
          + t[i].isDaemon());
      while(true)
        yield();
  }
}
    class DaemonSpawn extends Thread {
    public DaemonSpawn(int i) {
      start();
      System.out.println("DaemonSpawn " + i + " started");
    }
    public void run() {
      while(true)
        yield();
    }
  }

  public class Daemons {
    private static Test monitor = new Test();
    public static void main(String[] args) throws Exception {
      Thread d = new Daemon();
      System.out.println("d.isDaemon() = " + d.isDaemon());
      // Allow the daemon threads to
      // finish their startup processes:
      Thread.sleep(1000);
      monitor.expect(new String[] {
        "d.isDaemon() = true",
        "DaemonSpawn 0 started",
        "DaemonSpawn 1 started",
        "DaemonSpawn 2 started",
        "DaemonSpawn 3 started",
        "DaemonSpawn 4 started",
        "DaemonSpawn 5 started",
        "DaemonSpawn 6 started",
        "DaemonSpawn 7 started",
        "DaemonSpawn 8 started",
        "DaemonSpawn 9 started",
        "t[0].isDaemon() = true",
        "t[1].isDaemon() = true",
        "t[2].isDaemon() = true",
        "t[3].isDaemon() = true",
        "t[4].isDaemon() = true",
        "t[5].isDaemon() = true",
        "t[6].isDaemon() = true",
        "t[7].isDaemon() = true",
        "t[8].isDaemon() = true",
        "t[9].isDaemon() = true"
    }, Test.IGNORE_ORDER + Test.WAIT);
  }
} ///:~

The Daemon thread sets its daemon flag to "true" and then spawns a bunch of other threads—which do not set themselves to daemon mode—to show that they are daemons anyway. Then it goes into an infinite loop that calls yield( ) to give up control to the other processes.

There's nothing to keep the program from terminating once main( ) finishes its job, since there are nothing but daemon threads running. So that you can see the results of starting all the daemon threads, the main( ) thread is put to sleep for a second. Without this, you see only some of the results from the creation of the daemon threads. (Try sleep( ) calls of various lengths to see this behavior.)

Joining a thread

One thread may call join( ) on another thread to wait for the second thread to complete before proceeding. If a thread calls t.join( ) on another thread t, then the calling thread is suspended until the target thread t finishes (when t.isAlive( ) is false).

You may also call join( ) with a timeout argument (in either milliseconds or milliseconds and nanoseconds) so that if the target thread doesn't finish in that period of time, the call to join( ) returns anyway.

The call to join( ) may be aborted by calling interrupt( ) on the calling thread, so a try-catch clause is required.

All of these operations are shown in the following example:

//: c13:Joining.java
// Understanding join().
import com.bruceeckel.simpletest.*;
 class Sleeper extends Thread {
  private int duration;
  public Sleeper(String name, int sleepTime) {
    super(name);
    duration = sleepTime;
    start();
  }
  public void run() {
    try {
      sleep(duration);
    } catch (InterruptedException e) {
      System.out.println(getName() + " was interrupted. " +
        "isInterrupted(): " + isInterrupted());
      return;
    }
    System.out.println(getName() + " has awakened");
   }
}

class Joiner extends Thread {
  private Sleeper sleeper;
  public Joiner(String name, Sleeper sleeper) {
    super(name);
    this.sleeper = sleeper;
    start();
  }
  public void run() {
    try {
      sleeper.join();
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
    System.out.println(getName() + " join completed");
  }
}

public class Joining {
  private static Test monitor = new Test();
  public static void main(String[] args) {
    Sleeper
      sleepy = new Sleeper("Sleepy", 1500),
      grumpy = new Sleeper("Grumpy", 1500);
    Joiner
      dopey = new Joiner("Dopey", sleepy),
      doc = new Joiner("Doc", grumpy);
    grumpy.interrupt();
    monitor.expect(new String[] {
      "Grumpy was interrupted. isInterrupted(): false",
      "Doc join completed",
      "Sleepy has awakened",
      "Dopey join completed"
    }, Test.AT_LEAST + Test.WAIT);
  }
} ///:~

A Sleeper is a type of Thread that goes to sleep for a time specified in its constructor. In run( ), the call to sleep( ) may terminate when the time expires, but it may also be interrupted. Inside the catch clause, the interruption is reported, along with the value of isInterrupted( ). When another thread calls interrupt( ) on this thread, a flag is set to indicate that the thread has been interrupted. However, this flag is cleared when the exception is caught, so the result will always be false inside the catch clause. The flag is used for other situations where a thread may examine its interrupted state apart from the exception.

A Joiner is a thread that waits for a Sleeper to wake up by calling join( ) on the Sleeper object. In main( ), each Sleeper has a Joiner, and you can see in the output that if the Sleeper is either interrupted or if it ends normally, the Joiner completes in conjunction with the Sleeper.

Coding variations

In the simple examples that you've seen so far, the thread objects are all inherited from Thread. This makes sense because the objects are clearly only being created as threads and have no other behavior. However, your class may already be inheriting from another class, in which case you can't also inherit from Thread (Java doesn't support multiple inheritance). In this case, you can use the alternative approach of implementing the Runnable interface. Runnable specifies only that there be a run( ) method implemented, and Thread also implements Runnable.

This example demonstrates the basics:

//: c13:RunnableThread.java
// SimpleThread using the Runnable interface.

public class RunnableThread implements Runnable {
  private int countDown = 5;
  public String toString() {
    return "#" + Thread.currentThread().getName() +
      ": " + countDown;
  }
  public void run() {
    while(true) {
      System.out.println(this);
      if(--countDown == 0) return;
    }
  }
  public static void main(String[] args) {
    for(int i = 1; i <= 5; i++)
      new Thread(new RunnableThread(), "" + i).start();
    // Output is like SimpleThread.java
  }
} ///:~

The only thing required by a Runnable class is a run( ) method, but if you want to do anything else to the Thread object (such as getName( ) in toString( )) you must explicitly get a reference to it by calling Thread.currentThread( ). This particular Thread constructor takes a Runnable and a name for the thread.

When something has a Runnable interface, it simply means that it has a run( ) method, but there's nothing special about that—it doesn't produce any innate threading abilities, like those of a class inherited from Thread. So to produce a thread from a Runnable object, you must create a separate Thread object as shown in this example, handing the Runnable object to the special Thread constructor. You can then call start( ) for that thread, which performs the usual initialization and then calls run( ).

The convenient aspect about the Runnable interface is that everything belongs to the same class; that is, Runnable allows a mixin in combination with a base class and other interfaces. If you need to access something, you simply do it without going through a separate object. However, inner classes have this same easy access to all the parts of an outer class, so member access is not a compelling reason to use Runnable as a mixin rather than an inner subclass of Thread.

When you use Runnable, you're generally saying that you want to create a process in a piece of code—implemented in the run( ) method—rather than an object representing that process. This is a matter of some debate, depending on whether you feel that it makes more sense to represent a thread as an object or as a completely different entity, a process.1 If you choose to think of it as a process, then you are freed from the object-oriented imperative that "everything is an object." This also means that there's no reason to make your whole class Runnable if you only want to start a process to drive some part of your program. Because of this, it often makes more sense to hide your threading code inside your class by using an inner class, as shown here:

//: c13:ThreadVariations.java
// Creating threads with inner classes.
import com.bruceeckel.simpletest.*;

// Using a named inner class:
class InnerThread1 {
  private int countDown = 5;
  private Inner inner;
  private class Inner extends Thread {
    Inner(String name) {
      super(name);
      start();
    }
    public void run() {
      while(true) {
        System.out.println(this);
        if(--countDown == 0) return;
        try {
          sleep(10);
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }
      }
    }
    public String toString() {
      return getName() + ": " + countDown;
    }
  }
  public InnerThread1(String name) {
    inner = new Inner(name);
  }
}

// Using an anonymous inner class:
class InnerThread2 {
  private int countDown = 5;
  private Thread t;
  public InnerThread2(String name) {
    t = new Thread(name) {
      public void run() {
        while(true) {
          System.out.println(this);
          if(--countDown == 0) return;
          try {
            sleep(10);
          } catch (InterruptedException e) {
            throw new RuntimeException(e);
          }
        }
      }
      public String toString() {
        return getName() + ": " + countDown;
      }
    };
    t.start();
  }
}

// Using a named Runnable implementation:
class InnerRunnable1 {
  private int countDown = 5;
  private Inner inner;
  private class Inner implements Runnable {
    Thread t;
    Inner(String name) {
      t = new Thread(this, name);
      t.start();
    }
    public void run() {
      while(true) {
        System.out.println(this);
        if(--countDown == 0) return;
        try {
          Thread.sleep(10);
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }
      }
    }
    public String toString() {
      return t.getName() + ": " + countDown;
    }
  }
  public InnerRunnable1(String name) {
    inner = new Inner(name);
  }
}

// Using an anonymous Runnable implementation:
class InnerRunnable2 {
  private int countDown = 5;
  private Thread t;
  public InnerRunnable2(String name) {
    t = new Thread(new Runnable() {
      public void run() {
        while(true) {
          System.out.println(this);
          if(--countDown == 0) return;
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            throw new RuntimeException(e);
          }
        }
      }
      public String toString() {
        return Thread.currentThread().getName() +
          ": " + countDown;
      }
    }, name);
    t.start();
  }
}

// A separate method to run some code as a thread:
class ThreadMethod {
  private int countDown = 5;
  private Thread t;
  private String name;
  public ThreadMethod(String name) { this.name = name; }
  public void runThread() {
    if(t == null) {
      t = new Thread(name) {
        public void run() {
          while(true) {
            System.out.println(this);
            if(--countDown == 0) return;
            try {
              sleep(10);
            } catch (InterruptedException e) {
              throw new RuntimeException(e);
            }
          }
        }
        public String toString() {
          return getName() + ": " + countDown;
        }
      };
      t.start();
    }
  }
}

public class ThreadVariations {
  private static Test monitor = new Test();
  public static void main(String[] args) {
    new InnerThread1("InnerThread1");
    new InnerThread2("InnerThread2");
    new InnerRunnable1("InnerRunnable1");
    new InnerRunnable2("InnerRunnable2");
    new ThreadMethod("ThreadMethod").runThread();
    monitor.expect(new String[] {
      "InnerThread1: 5",
      "InnerThread2: 5",
      "InnerThread2: 4",
      "InnerRunnable1: 5",
      "InnerThread1: 4",
      "InnerRunnable2: 5",
      "ThreadMethod: 5",
      "InnerRunnable1: 4",
      "InnerThread2: 3",
      "InnerRunnable2: 4",
      "ThreadMethod: 4",
      "InnerThread1: 3",
      "InnerRunnable1: 3",
      "ThreadMethod: 3",
      "InnerThread1: 2",
      "InnerThread2: 2",
      "InnerRunnable2: 3",
      "InnerThread2: 1",
      "InnerRunnable2: 2",
      "InnerRunnable1: 2",
      "ThreadMethod: 2",
      "InnerThread1: 1",
      "InnerRunnable1: 1",
      "InnerRunnable2: 1",
      "ThreadMethod: 1"
    }, Test.IGNORE_ORDER + Test.WAIT);
  }
} ///:~

InnerThread1 creates a named inner class that extends Thread, and makes an instance of this inner class inside the constructor. This makes sense if the inner class has special capabilities (new methods) that you need to access in other methods. However, most of the time the reason for creating a thread is only to use the Thread capabilities, so it's not necessary to create a named inner class. InnerThread2 shows the alternative: An anonymous inner subclass of Thread is created inside the constructor and is upcast to a Thread reference t. If other methods of the class need to access t, they can do so through the Thread interface, and they don't need to know the exact type of the object.

The third and fourth classes in the example repeat the first two classes, but they use the Runnable interface rather than the Thread class. This is just to show that Runnable doesn't buy you anything more in this situation, but is in fact slightly more complicated to code (and to read the code). As a result, my inclination is to use Thread unless I'm somehow compelled to use Runnable.

The ThreadMethod class shows the creation of a thread inside a method. You call the method when you're ready to run the thread, and the method returns after the thread begins. If the thread is only performing an auxiliary operation rather than being fundamental to the class, this is probably a more useful/appropriate approach than starting a thread inside the constructor of the class.

Creating responsive user interfaces

As stated earlier, one of the motivations for using threading is to create a responsive user interface. Although we won't get to graphical user interfaces until Chapter 14, you can see a simple example of a console-based user interface. The following example has two versions: one that gets stuck in a calculation and thus can never read console input, and a second that puts the calculation inside a thread and thus can be performing the calculation and listening for console input.

//: c13:ResponsiveUI.java
// User interface responsiveness.
import com.bruceeckel.simpletest.*;

class UnresponsiveUI {
  private volatile double d = 1;
  public UnresponsiveUI() throws Exception {
    while(d > 0)
      d = d + (Math.PI + Math.E) / d;
    System.in.read(); // Never gets here
  }
}

public class ResponsiveUI extends Thread {
  private static Test monitor = new Test();
  private static volatile double d = 1;
  public ResponsiveUI() {
    setDaemon(true);
    start();
  }
  public void run() {
    while(true) {
      d = d + (Math.PI + Math.E) / d;
    }
  }
  public static void main(String[] args) throws Exception {
    //! new UnresponsiveUI(); // Must kill this process
    new ResponsiveUI();
    Thread.sleep(300);
    System.in.read(); // 'monitor' provides input
    System.out.println(d); // Shows progress
  }
} ///:~

UnresponsiveUI performs a calculation inside an infinite while loop, so it can obviously never reach the console input line (the compiler is fooled into believing that the input line is reachable by the while conditional). If you run the program with the line that creates an UnresponsiveUI uncommented, you'll have to kill the process to get out.

To make the program responsive, putting the calculation inside a run( ) method allows it to be preempted, and when you press the Enter key you'll see that the calculation has indeed been running in the background while waiting for your user input (for testing purposes, the console input line is automatically provided to System.in.read( ) by the com.bruceeckel.simpletest.Test object, which is explained in Chapter 15).

  • + Share This
  • 🔖 Save To Your Account