JaVa
   

Using the Runnable Interface

So far we have created a thread by extending the Thread class, thus dedicating our own class to being a subclass of Thread. As Java does not support multiple inheritance (the ability for a given class to extend more than one other class), it is quite likely that we would not want to make a class just a thread or even go the lengths of typing out a dedicated nested class that extends the Thread class. For example, a little later on in this tutorial we will create an applet class that is also used to define the run method for a thread to execute. An applet is the Java program that runs embedded in a web browser, defined generally by the java.awt.Applet class. The basic creation of an applet entails extending the java.awt.Applet class as follows. (Don't worry too much! We will look at applets in detail in the next few chapters.)

public class MyClass extends Applet
{
}


However, we would not be able to do the following:

public class MyClass extends Applet, Thread
{
 // No multiple inheritance!!!
}


What we can do is implement the Runnable interface, which requires the inclusion of the run method in our implementing class. We can then say that an instance of our class is both of type Applet and of type Runnable. We can then create a new thread, passing a runnable object to the constructor. The following example, SimpleThread2, illustrates creating a thread with a runnable object.

Code Listing 7-2: SimpleThread2.java
public class SimpleThread2 implements Runnable
{
 public void run()
 {
 System.out.println("New thread executing");
 }
 public static void main(String args[])
 {
 SimpleThread2 runner = new SimpleThread2();
 Thread myThread = new Thread(runner);
 myThread.start();
 System.out.println("Main's thread executing");
 }
}


Java End example

This code behaves in the same way as the previous example, and running this example will give one of the two previous possible outputs.

NoteĀ 

You can give a thread a name, which is merely a string value that it stores but makes debugging easier. You can use one of the constructors that supports a name parameter string or the setName method that takes a string argument to set the name of a thread. You can also use the getName method to retrieve the name of a thread. To find the name of the currently running thread, you would use the following code:

String threadName = Thread.currentThread().getName();
JaVa
   
Comments