Gurgaon Jobs, Companies and Consultants

Those who are looking for job in Gurgaon can visit this site : Gurgaon Jobs. Here you will find email ids/contact no of "Companies in Gurgaon" and also of "Placement Consultants in Gurgaon"

Wednesday, April 08, 2009

Java Threads : Implement Runnable vs Extend Thread

Approach 1 :

class RunnableEgClass implements Runnable {

public boolean printThreadName;

public void run() {

if(printThreadName) {
System.out.println("Name : " + Thread.currentThread().getName());
}

}

}


Approach 2 :

class ThreadEgClass extends Thread {

public boolean printThreadName;

public void run() {

if(printThreadName) {
System.out.println("Name : " + Thread.currentThread().getName());
}

}

}


Usage of both :

public class TestThreads {

public static void main(String args[]) {

// Create 3 threads using approach 1
RunnableEgClass sharedObject = new RunnableEgClass();
sharedObject.printThreadName = true;

//Now u can use this same object and create n threads by passing it in constructor
Thread thread1 = new Thread(sharedObject); thread1.start();
Thread thread2 = new Thread(sharedObject); thread2.start();
Thread thread3 = new Thread(sharedObject); thread3.start();

// Create 3 threads using approach 2
ThreadEgClass thread4 = new ThreadEgClass();
thread4.printThreadName = true;
thread4 .start();

ThreadEgClass thread5 = new ThreadEgClass();thread5 .start();
thread5.printThreadName = true;
thread5.start();

ThreadEgClass thread6 = new ThreadEgClass();
thread6.printThreadName = true;
thread6 .start();
}
}


Two basic differences :

1. In Runnable each Thread is sharing same object whose run method will be called
but in extend each Thread is unique object. So Runnable allows sharing object across threads.
So if u see above example with Approach 1 we just need to set printThreadName once for all
three threads.
But with Approach 2 we need to set printThreadName three times for each thread. Clearly saving few lines of code.

2. After Extending Thread class that class will not be able to extend any other class. Multiple
Inheritance not supported in java.

1 comment:

pari@parimalapriya said...
This comment has been removed by the author.