It is a big question, even in interviews, which style of creation of thread is preferable. Explained in simple terms. Start reading.
Thread creation styles
There are two ways of creating threads – one by extending Thread class and the other by implementing Runnable interface. Now the discussion is which to prefer in normal situations.
I put both for an eye glance here before reasoning starts.
// extending Thread class
public class Demo extends Thread
{
public void run() { }
public static void main(String args[])
{
Demo d1 = new Demo();
d1.start();
}
}
// by implementing Runnable interface
public class Demo implements Runnable
{
public void run() { }
public static void main(String args[])
{
Demo d1 = new Demo();
Thread t1 = new Thread(d1) // composition
t1.start();
}
}
Extends Thread vs Implements Runnable
- We extend some class either to use the class as it is or modify the behaviour of its methods by overriding. We are not changing the behaviour of Thread class. Just we are interested to use start() and sleep() methods etc. as it is (with the original behaviour intended by the Designers). So better use Thread class by composition by implementing Runnable interface.
- Advantage of implementing Runnable is, at the same time, we can extend another class as follows (remember, Java does not support multiple inheritance).
- Interface always gives a cleaner separation between your code and Thread class methods implementation.
- When Thread is extended, d1 object becomes implicitly a thread and starting it as a thread itself with d1.start(). When Demo is implemented with Runnable, d1 is not a thread at all. You are taking the help of a Thread object t1 to execute Demo class run() method. This is better approach as you can pass d1 object to any other service that can call run() method. Thus the code becomes more flexible in larger applications.
- When Thread is extended, each thread created should be started separately. But with Runnable, the same t1 service can be used to start many threads one by one.
public class Animation extends Applet implements Runnable
In the above code, Animation class can make use Applet class methods to run in a browser. Also can make use of Thread class methods by composition (like t1.start()).
Hi sir,
I have got a doubt. You said when Demo implements Runnable interface then d1 object is not thread at all i did not get this point. Could you please tell me why d1 object is not thread at all.
Thanks
Adi
By definition, if you extend Thread class, then the object created becomes implicitly thread. Otherway to say perfectly, the object of the class can make use of the Thread class methods to create thread. When you implement Runnable, the class cannot make use of the Thread class methods (like start()) and thereby I call myself, the object is not thread.