This section provides a tutorial example on how to create new threads with the 'Thread' class and runnable objects, which are created with classes that implements the 'Runnable' interface.
The second way to create a new thread is to:
Implement the "Runnable" interface in your own class.
Implement the run() method defined in the "Runnable" interface in your own class.
Instantiate a runnable object of your own class.
Instantiate a thread object of the "Thread" class with the runnable object specified.
Call the start() method on the new object.
Here is a tutorial sample program showing you how to do this:
class HelloRunnable implements Runnable {
public static void main(String[] a) {
HelloRunnable r = new HelloRunnable();
Thread t = new Thread(r);
t.start();
System.out.println("Hello world! - From the main program.");
}
public void run() {
System.out.println("Hello world! - From a thread.");
try {
Thread.sleep(1000*60*60);
} catch (InterruptedException e) {
System.out.println("Interrupted.");
}
}
}
Output:
Hello world! - From the main program.
Hello world! - From a thread.
Note that:
The program behaves the same way as the previous program: HelloThread.
The Thread object t is created with the special Thread constructor,
which takes a Runnable object as input. If you start a Thread object created
in this way, the run() method of the Runnable object will be executed as
a new thread.
Since our class is not extending the Thread class any more, we need to
call the sleep() explicitly by prefixing the class name: Thread.
May be you are wondering why we need the second way of creating a new thread,
which seems to be less straight forward than the first way? The answer is that
Java classes can not be extended from two different base classes. So if you are
in a situation where you want to create a new class by extending an existing
class to inherit some nice features of that class, and you also want to make
the new class executable as a thread, you have to use the second way to implement
the "Runnable" interface in your new class.