9.3 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 method prototype 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. The 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 Thread class is created by passing a Runnable object as argument to the Thread constructor. 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.

The run() method of the Runnable object is eventually executed by the thread represented by the Thread object on which the start() method was invoked. This sequence of events is illustrated in Figure 9.1.

Figure 9.1. Spawning Threads Using a Runnable Object

graphics/09fig01.gif

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 using 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 argument.

void run()

The Thread class implements the Runnable interface by providing an implementation of the run() method. This implementation does nothing. Subclasses of the Thread class should override this method.

If the current thread is created using a separate Runnable object, then the Runnable object's run() method 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, that is, 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 was already started.


In Example 9.1, the class Counter implements the Runnable interface. The constructor for the Counter class ensures that each object of the Counter class will create a new thread by passing the Counter instance to the Thread constructor, as shown at (1). In addition, the thread is enabled for execution by the call to its start() method, as shown at (2). At (3), the class defines the run() method that constitutes the code executed by the thread. In each iteration the thread will sleep for 250 milliseconds after writing the current value of the counter, as shown at (4). While it is sleeping, other threads may run (see Section 9.5, p. 370).

Example 9.1 Implementing the Runnable Interface
class Counter implements Runnable {

    private int currentValue;

    private Thread worker;

    public Counter(String threadName) {
        currentValue = 0;
        worker = new Thread(this, threadName);   // (1) Create a new thread.
        System.out.println(worker);
        worker.start();                          // (2) Start the thread.
    }

    public int getValue() { return currentValue; }

    public void run() {                          // (3) Thread entry point
        try {
            while (currentValue < 5) {
                System.out.println(worker.getName() + ": " + (currentValue++));
                Thread.sleep(250);               // (4) Current thread sleeps.
            }
        } catch (InterruptedException e) {
            System.out.println(worker.getName() + " interrupted.");
        }
        System.out.println("Exit from thread: " + worker.getName());
    }
}

public class Client {
    public static void main(String[] args) {
        Counter counterA = new Counter("Counter A"); // (5) Create a thread.

        try {
            int val;
            do {
                val = counterA.getValue();       // (6) Access the counter value.
                System.out.println("Counter value read by main thread: " + val);
                Thread.sleep(1000);              // (7) Current thread sleeps.
            } while (val < 5);
        } catch (InterruptedException e) {
            System.out.println("main thread 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 class Counter at (5) and retrieves its value in a loop at (6). After each retrieval, it sleeps for 1,000 milliseconds at (7), 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 thread, giving the Counter thread the opportunity to run as well. The Counter thread is a child thread of the main thread. It inherits the user-thread status from the main thread. If the code after statement at (5) 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.

Since thread scheduling is not predictable and Example 9.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 a Thread object: its name (Counter A), its priority (5), and its parent thread (main). The output from the main thread and the Counter A thread is interleaved. Not surprisingly, 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 9.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 9.2. Spawning Threads?Extending the Thread Class

graphics/09fig02.gif

In Example 9.2, the Counter class from Example 9.1 has been modified to illustrate 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.

The static method currentThread() in the Thread class can be used to obtain a reference to the Thread object associated with the current thread. An example of its usage is shown at (5) in Example 9.2:

Thread.currentThread().getName());   // (5) Current thread

Adding the following statement before the call to the start() method at (2) in Example 9.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.

Example 9.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);
        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.

In Examples 9.1 and 9.2, the Thread object was created and the start() method called immediately to initiate the thread execution, as shown at (2). There are other ways of starting a thread. The call to the start() method can be factored out of the constructor, and the method can be called later, using a reference that denotes the thread object.

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();


     
    ASPTreeView.com
     
    Evaluation has РАјС»СНФ»јШexpired.
    Info...