Extending Thread Assignment Help

Assignment Help: >> Threads - Extending Thread

Extending Thread:

The second way to create a thread is to made a new class which extends Thread, and then to create an object of that class. This extending class must override the run ( ) method, that is the entry point for the new thread.  That must also call start ( ) to start execution of the new thread. Given is the preceding program rewritten to extend Thread.

1. Create a second thread through extending thread

2. Class NewThread extends Thread {

3. NewThread(){

/ / Create a new, second thread

super ("Demo Thread");

System.out.println ("Child thread:" + this );

start ( ); / / start the thread

}

/ / This is the entry point for the second thread.

public void run ( ) {

try {

for (int i=5; i > 0; i - -) {

System.out.println ("Child Thread:" + i);

Thread.sleep (500);

}

}catch (InterrruptedException e ) {

System.out.println ("Child interrupted.");

}

System.out.println ("Exiting child thread,");

}

}

class extendThread {

public static void main (String args [ ] ) {

new NewThread ( );

try {

for (int i =5; i> 0; i - -){

System.out.println ("Main Thread:" + i);

Thread.sleep (1000);

}

}catch (InterruptedException e ) {

System.out.println ("Main thread interrupted.");

}

System.out.println ("Main thread exiting .");

}

}

This program produces the similar output as the preceding version. As you could see, the child thread is created through instantiating an object of NewThread that is derived from Thread.

Remember the call to super ( ) inside NewThread. This invokes the subsequent form of the Thread constructor:

public Thread (String threadName)

In the above program, threadName specifies the name of the thread.

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd