Difference between Runnable vs Thread in Java

In java language, as we all know that there are two ways to create threads. One using Runnable interface and another by extending Thread class. Let’s identify the differences between both ways i.e extends thread and implements runnable.

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.

  1. 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.
  2. Java only supports single inheritance, so you can only extend one class.
  3. Instantiating an interface gives a cleaner separation between your code and the implementation of threads.
  4. Implementing Runnable makes your class more flexible. If you extend Thread then the action you’re doing is always going to be in a thread. However, if you implement Runnable 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.
  5. 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 its start() 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. If you know something more, please put that in comments section and I will include in post content.

Happy Learning !!

Leave a Reply

19 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial