1. Create Thread using Runnable Interface vs Thread class
Let’s quickly check the java code of usage of both techniques.
1.1. Runnable interface
Java program to create thread by implementing Runnable interface.
public class DemoRunnable implements Runnable { public void run() { //Code } } //start new thread with a "new Thread(new demoRunnable()).start()" call
1.2. Thread class
Java program to create thread by extending Thread class.
public class DemoThread extends Thread { public DemoThread() { super("DemoThread"); } public void run() { //Code } } //start new thread with a "new demoThread().start()" call
2. Difference between Runnable vs Thread
There has been a good amount of debate on which is better way. Well, I also tried to find out and below is my learning.
- Implementing
Runnable
is the preferred way to do it. Here, you’re not really specializing or modifying the thread’s behavior. You’re just giving the thread something to run. That means composition is the better way to go. - Java only supports single inheritance, so you can only extend one class.
- Instantiating an interface gives a cleaner separation between your code and the implementation of threads.
- Implementing
Runnable
makes your class more flexible. If you extendThread
then the action you’re doing is always going to be in a thread. However, if you implementRunnable
it doesn’t have to be. You can run it in a thread, or pass it to some kind of executor service, or just pass it around as a task within a single threaded application. - If you are working on JDK 4 or lesser, then there is bug :http://bugs.java.com/bugdatabase/view_bug.do;jsessionid=5869e03fee226ffffffffc40d4fa881a86e3:WuuT?bug_id=4533087
It’s fixed in Java 1.5 but Sun doesn’t intend to fix it in 1.4.
The issue is that at construction time, a
Thread
is added to a list of references in an internal thread table. It won’t get removed from that list until itsstart()
method has completed. As long as that reference is there, it won’t get garbage collected.
That’s all about differences between Runnable
interface and Thread
class in java.
Leave a Reply