Tuesday, June 9, 2015

Extending Thread Class


public class MainActivity
{
public static void main(String[] args)
{
ExtendingThreadClass obj = new ExtendingThreadClass("THREAD_A");
obj.run();

ExtendingThreadClass obj2 = new ExtendingThreadClass("THREAD_B");
obj2.run();
}
}

----------------------------------------------


public class ExtendingThreadClass extends Thread{

Thread t ; 
String threadName;
public ExtendingThreadClass(String threadName) 
{
this.threadName = threadName;
System.out.println("Creating thread obj: "+ threadName);
}
@Override
public void run() 
{
super.run();
System.out.println("Running thread: "+ threadName);
try {
for(int i = 4; i > 0 ; i-- ){
System.out.println("thread: "+ threadName +" "+  i);
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread: "+ threadName + " interrupted.");
e.printStackTrace();
}
System.out.println("Thread: "+ threadName +" is exiting");
}
public void start()
{
System.out.println("Starting: "+ threadName);
if(t == null){
t = new Thread(this, threadName);
t.start();
}
}
}

--------------------------------------------------------


No comments:

Post a Comment