Thread examples for extending



The extending class must override the method run() mehtod. Which is the entry point of the new thread.It must also call the start() to begin execution of the new thread.
Here is the proceding program rewritten to extend thread

Ex#1:

//create a second thread by extending Thread

class NewThread extends Thread{
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 (InterruptedException e) {
System.out.println(“child interrupted.”);
}
System.out.println(“Exiting child thread”);
}
}
class ExtendThread{
public static void main(String args[]){
new NewThread();  //create a new thread
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”);
}
}

Share with SociBook.com

Random Posts

Post a Comment