Extending The Thread Class in Advanced Java Programming

Home  »  Java  »  Advance Java »  »  MultiThreading »  Extending The Thread Class

The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run() method, which is entry point for the new thread. It must also call strat() to begin execution of the new thread.

Examnple
The following example creates a subclass of the Thread class and overrides the run() method of the Thread class.
The run() method is called when the thread starts executing. To start the thread, call the start() method of the Thread class.



Once the thread is subclassed, to start the thread, the object of the class is created by instantiating the MyThread class.

MyThread myThread1=new MyThread(this);
myThread1.start();

  1. The first statement creates an object of the MyThread class and calls the constructor of the class by passing the reference of the thread object to MyThread class using the this reference.

  2. The Second statement used the start() method of the Thread class, which is overriden in the MyThread class. The start() method in turn calls the run() method.

The following is an example which uses extends Thread:



The above code will be stored in the file called ExtendThread.java, which on compilation will crate a class file called ExtendThread.class. Now compile this file using below commands in the DOS mode:

C:\>jdk1.4\bin>javac ExtendThread.java
C:\>jdk1.4\bin>java ExtendThread




"Output of ExtendThread.class"


Download Complete Program

  -  




MultiThreading


Thread Life Cycle Main Thread
Creating A Thread Thread Priority
Extending The Thread Class Writing Applets With Threads




No comments:

Post a Comment