Home > Articles > Programming > Java

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

13.4 Thread Creation

A thread in Java is represented by an object of the Thread class. Implementing threads is achieved in one of two ways:

  • implementing the java.lang.Runnable interface
  • extending the java.lang.Thread class

Implementing the Runnable Interface

The Runnable interface has the following specification, comprising one abstract method declaration:

public interface Runnable {
  void run();
}

A thread, which is created based on an object that implements the Runnable interface, will execute the code defined in the public method run(). In other words, the code in the run() method defines an independent path of execution and thereby the entry and the exits for the thread. A thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.

The procedure for creating threads based on the Runnable interface is as follows:

  1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.
  2. An object of the Thread class is created by passing a Runnable object as an argument in the Thread constructor call. The Thread object now has a Runnable object that implements the run() method.
  3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned. In other words, the call to the start() method is asynchronous.

When the thread, represented by the Thread object on which the start() method was invoked, gets to run, it executes the run() method of the Runnable object. This sequence of events is illustrated in Figure 13.1.

Figure 13.1

Figure 13.1 Spawning Threads Using a Runnable Object

The following is a summary of important constructors and methods from the java.lang.Thread class:

  • Thread(Runnable threadTarget)
    Thread(Runnable threadTarget, String threadName)

    The argument threadTarget is the object whose run() method will be executed when the thread is started. The argument threadName can be specified to give an explicit name for the thread, rather than an automatically generated one. A thread’s name can be retrieved by calling the getName() method.

  • static Thread currentThread()

    This method returns a reference to the Thread object of the currently executing thread.

  • final String getName()
    final void setName(String name)

    The first method returns the name of the thread. The second one sets the thread’s name to the specified argument.

  • void run()

    The Thread class implements the Runnable interface by providing an implementation of the run() method. This implementation in the Thread class does nothing and returns. Subclasses of the Thread class should override this method. If the current thread is created using a separate Runnable object, the run() method of the Runnable object is called.

  • final void setDaemon(boolean flag)
    final boolean isDaemon()

    The first method sets the status of the thread either as a daemon thread or as a user thread, depending on whether the argument is true or false, respectively. The status should be set before the thread is started. The second method returns true if the thread is a daemon thread, otherwise, false.

  • void start()

    This method spawns a new thread, i.e., the new thread will begin execution as a child thread of the current thread. The spawning is done asynchronously as the call to this method returns immediately. It throws an IllegalThreadStateException if the thread is already started.

In Example 13.1, the class Counter implements the Runnable interface. At (1), the class defines the run() method that constitutes the code to be executed in a thread. In each iteration of the while loop, the current value of the counter is printed and incremented, as shown at (2). Also, in each iteration, the thread will sleep for 250 milliseconds, as shown at (3). While it is sleeping, other threads may run (see Section 13.6, p. 640).

The code in the main() method ensures that the Counter object created at (4) is passed to a new Thread object in the constructor call, as shown at (5). In addition, the thread is enabled for execution by the call to its start() method, as shown at (6).

The static method currentThread() in the Thread class can be used to obtain a reference to the Thread object associated with the current thread. We can call the getName() method on the current thread to obtain its name. An example of its usage is shown at (2), that prints the name of the thread executing the run() method. Another example of its usage is shown at (8), that prints the name of the thread executing the main() method.

Example 13.1. Implementing the Runnable Interface

class Counter implements Runnable {
  private int currentValue;
  public Counter() { currentValue = 0; }
  public int getValue() { return currentValue; }

  public void run() {                            // (1) Thread entry point
    try {
      while (currentValue < 5) {
        System.out.println(
            Thread.currentThread().getName()     // (2) Print thread name.
            + ": " + (currentValue++)
        );
        Thread.sleep(250);                       // (3) Current thread sleeps.
      }
    } catch (InterruptedException e) {
      System.out.println(Thread.currentThread().getName() + " interrupted.");
    }
    System.out.println("Exit from thread: " + Thread.currentThread().getName());
  }
}
//_______________________________________________________________________________
public class Client {
  public static void main(String[] args) {
    Counter counterA = new Counter();                 // (4) Create a counter.
    Thread worker = new Thread(counterA, "Counter A");// (5) Create a new thread.
    System.out.println(worker);
    worker.start();                                   // (6) Start the thread.

    try {
      int val;
      do {
        val = counterA.getValue();               // (7) Access the counter value.
        System.out.println(
            "Counter value read by " +
            Thread.currentThread().getName() +   // (8) Print thread name.
            ": " + val
        );
        Thread.sleep(1000);                      // (9) Current thread sleeps.
      } while (val < 5);
    } catch (InterruptedException e) {
      System.out.println("The main thread is interrupted.");
    }

    System.out.println("Exit from main() method.");
  }
}

Possible output from the program:

Thread[Counter A,5,main]
Counter value read by main thread: 0
Counter A: 0
Counter A: 1
Counter A: 2
Counter A: 3
Counter value read by main thread: 4
Counter A: 4
Exit from thread: Counter A
Counter value read by main thread: 5
Exit from main() method.

The Client class uses the Counter class. It creates an object of the class Counter at (4) and retrieves its value in a loop at (7). After each retrieval, the main thread sleeps for 1,000 milliseconds at (9), allowing other threads to run.

Note that the main thread executing in the Client class sleeps for a longer time between iterations than the Counter A thread, giving the Counter A thread the opportunity to run as well. The Counter A thread is a child thread of the main thread. It inherits the user-thread status from the main thread. If the code after the statement at (6) in the main() method was removed, the main thread would finish executing before the child thread. However, the program would continue running until the child thread completed its execution.

Since thread scheduling is not predictable (Section 13.6, p. 638) and Example 13.1 does not enforce any synchronization between the two threads in accessing the counter value, the output shown may vary. The first line of the output shows the string representation of the Thread object associated with the counter: its name (Counter A), its priority (5), and its parent thread (main). The output from the main thread and the Counter A thread is interspersed. It also shows that the value in the Counter A thread was incremented faster than the main thread could access the counter’s value after each increment.

Extending the Thread Class

A class can also extend the Thread class to create a thread. A typical procedure for doing this is as follows (see Figure 13.2):

  1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.
  2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call.
  3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.
Figure 13.2

Figure 13.2 Spawning Threads—Extending the Thread Class

In Example 13.2, the Counter class from Example 13.1 has been modified to illustrate creating a thread by extending the Thread class. Note the call to the constructor of the superclass Thread at (1) and the invocation of the inherited start() method at (2) in the constructor of the Counter class. The program output shows that the Client class creates two threads and exits, but the program continues running until the child threads have completed. The two child threads are independent, each having its own counter and executing its own run() method.

The Thread class implements the Runnable interface, which means that this approach is not much different from implementing the Runnable interface directly. The only difference is that the roles of the Runnable object and the Thread object are combined in a single object.

Adding the following statement before the call to the start() method at (2) in Example 13.2:

setDaemon(true);

illustrates the daemon nature of threads. The program execution will now terminate after the main thread has completed, without waiting for the daemon Counter threads to finish normally:

Method main() runs in thread main
Thread[Counter A,5,main]
Thread[Counter B,5,main]
Counter A: 0
Exit from main() method.
Counter B: 0

Example 13.2. Extending the Thread Class

class Counter extends Thread {

  private int currentValue;

  public Counter(String threadName) {
    super(threadName);                           // (1) Initialize thread.
    currentValue = 0;
    System.out.println(this);
//  setDaemon(true);
    start();                                     // (2) Start this thread.
  }

  public int getValue() { return currentValue; }

  public void run() {                            // (3) Override from superclass.
    try {
      while (currentValue < 5) {
        System.out.println(getName() + ": " + (currentValue++));
        Thread.sleep(250);                       // (4) Current thread sleeps.
      }
    } catch (InterruptedException e) {
      System.out.println(getName() + " interrupted.");
    }
    System.out.println("Exit from thread: " + getName());
  }
}
//_______________________________________________________________________________
public class Client {
  public static void main(String[] args) {

    System.out.println("Method main() runs in thread " +
        Thread.currentThread().getName());       // (5) Current thread

    Counter counterA = new Counter("Counter A"); // (6) Create a thread.
    Counter counterB = new Counter("Counter B"); // (7) Create a thread.

    System.out.println("Exit from main() method.");
  }
}

Possible output from the program:

Method main() runs in thread main
Thread[Counter A,5,main]
Thread[Counter B,5,main]
Exit from main() method.
Counter A: 0
Counter B: 0
Counter A: 1
Counter B: 1
Counter A: 2
Counter B: 2
Counter A: 3
Counter B: 3
Counter A: 4
Counter B: 4
Exit from thread: Counter A
Exit from thread: Counter B

When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class:

  • Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface has this option.
  • A class might only be interested in being runnable and, therefore, inheriting the full overhead of the Thread class would be excessive.

The two previous examples illustrated two different ways to create a thread. In Example 13.1 the code to create the Thread object and call the start() method to initiate the thread execution is in the client code, not in the Counter class. In Example 13.2, this functionality is in the constructor of the Counter class, not in the client code.

Inner classes are useful for implementing threads that do simple tasks. The anonymous class below will create a thread and start it:

(new Thread() {
   public void run() {
     for(;;) System.out.println("Stop the world!");
   }
 }
).start();
  • + Share This
  • 🔖 Save To Your Account