HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

Difference between Runnable vs Thread in Java

By Lokesh Gupta | Filed Under: Java Concurrency

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 !!

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

17
Leave a Reply

This comment form is under antispam protection
7 Comment threads
10 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
14 Comment authors
This comment form is under antispam protection
  Subscribe  
newest oldest most voted
Notify of
Soumyaranjan

By implementing Runnable interface, we can only override the run() method. But when we extend Thread class, we can use many methods based on our requirements. If we want to make our class as a thread, we can always go for extending the Thread class rather than implementing Runnable interface.

Vote Up1Vote Down  Reply
7 months ago
Rahul Kashyap

Hello Sowmya rajan,

As per my understanding, Thread is a curse in java. If you create multiple threads then there would be a chance of memory overhead and hence the performance of the app will go down.

Vote Up0Vote Down  Reply
5 months ago
Akash

why we extends a thread class and what are the advantage of it

Vote Up0Vote Down  Reply
2 years ago
Ashish

Well Explained. Thanks to Lokesh !

Vote Up0Vote Down  Reply
3 years ago
Naveen

Good points on topic

Thanks lokesh..

Vote Up0Vote Down  Reply
2 years ago
Gopi

As per my knowledge, the advantage is – when there are multiple threads then, memory usage would be more in case of extends Thread. Because, each of your threads contains unique object associated with it. Where as, memory usage would be less in case of implements Runnable. Because, many threads can share the same runnable instance.

Vote Up0Vote Down  Reply
4 years ago
Lokesh Gupta

You are right Gopi. Point 5 state the same thought as you. Key thing is that it “CAN” share (as you also said); not always.

Vote Up0Vote Down  Reply
4 years ago
sreenath

Awesome explanation !!
Small correction in point 4

It should be ” implements Runnable” Not “extend Runnable”

Vote Up0Vote Down  Reply
5 years ago
pratik

i want what the main difference in the thread & and Runnable interface?

Vote Up0Vote Down  Reply
5 years ago
Manoj

5) By extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same runnable instance. – This statement seems wrong to me.

Many threads can share the same Thread object, same as Runnable instance.
For example,
public class A1 implements Runnable {….}
public class B1 extends Thread {….}

public class ABMain {
public static void main( String[] args ) {
A1 a = new A1(); //Create runnable instance
B1 b = new B1(); // Create Thread instance

new Thread( a ).start(); //Starts runnable instance

new Thread( b ).start(); //Starts Thread instance.

new Thread( a ).start(); // 2nd thread sharing same runnable instance A1
new Thread( b ).start(); // 2nd thread sharing same Thread instance.

}
}

Difference between Thread and Runnable I found is, Thread class provides apis to configure Thread instance based on your need.
If you extends Thread class, then
1. you will have flexibility to set priority to Thread instance,
2. you can create daemon thread,
3. you can check if thread is terminated, alive etc.

Vote Up0Vote Down  Reply
5 years ago
Manoj

There are apis available in Thread class which is not avaialbe in Runnable. Those apis helps developers to configure Thread properties.

Vote Up0Vote Down  Reply
5 years ago
Lokesh Gupta

I modified your program a little bit, to correct the picture of usage of thread and runnable.

class A1 implements Runnable {
private int counter = 0;
@Override
public void run() {
counter++;
System.out.println("Running A1 -> " + counter);
}
}

class B1 extends Thread {
private int counter = 0;
@Override
public void run() {
counter++;
System.out.println("Running B1 -> " + counter);
}
}

public class ABMain {
public static void main(String[] args) throws InterruptedException {
A1 a = new A1(); // Create runnable instance
B1 b = new B1(); // Create Thread instance

new Thread(a).start();
Thread.sleep(1000);
new Thread(a).start();
Thread.sleep(1000);
new Thread(a).start();
Thread.sleep(1000);

new B1().start();
Thread.sleep(1000);
new B1().start();
Thread.sleep(1000);
new B1().start();
}
}

Output:

1
2
3

1
1
1

1) A1 a = new A1(); does not make a thread. It’s just another class with no extra behavior. If you call A1.run() then it is not new thread. And A1.start() is not available to this class.
2) Only way to create start a thread in java is calling it’s start method.
3) If you look at constructor of Thread class, no constructor takes parameter of Thread class itself. And we know that Thread implements Runnable, effectively any call such as “new Thread(a).start();” is starting a thread with runnable mechanism.
4) Correct way to start thread (“using extend”) is calling it’s start method only directly.
e.g. new B1().start();
5) So effectively, in both techniques in your code, you are doing the same thing i.e. implementing runnable.

Vote Up0Vote Down  Reply
5 years ago
satish Kumar Singh

It’s correct post.

Vote Up0Vote Down  Reply
5 years ago
Dhruv

By extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same runnable instance.

The statement is alright but what is the advantage we gain here ?

Vote Up0Vote Down  Reply
5 years ago
Ashwini

The code is misleading. It doesn’t match the intent. It’s true that Thread class itself implements Runnable interface, so any instance of a class extending the Thread class can be passed in to creating new thread.

ExtendsThread et = new ExtendsThread(); 
Thread tc1 = new Thread(et); tc1.start(); 
Thread tc2 = new Thread(et); tc2.start();

These two threads share the same instance.

Vote Up0Vote Down  Reply
1 year ago
Lokesh Gupta

You have a point. Removing the statement from above post this until I find a reason to include.

Vote Up0Vote Down  Reply
1 year ago
Sanchita Vijayvargiya

Thank you for the post. It’s very helpful.

Vote Up0Vote Down  Reply
6 years ago

Search Tutorials

Java Concurrency Tutorial

  • Java Concurrency – Introduction
  • Concurrency Evolution
  • Thread Safety
  • Concurrency vs. Parallelism
  • Compare and Swap [CAS]
  • synchronized keyword
  • Object vs. Class Level Locking
  • Runnable vs. Thread
  • wait(), notify() and notifyAll()
  • Yield() vs. Join()
  • Sleep() vs. Wait()
  • Lock vs. Monitor
  • Callable + Future
  • UncaughtExceptionHandler
  • Throttling Task Submission
  • Executor Best Practices
  • Inter-thread Communication
  • Write and Resolve Deadlock

Java Concurrency Utilities

  • AtomicInteger
  • Lock
  • ThreadFactory
  • ThreadLocal
  • ExecutorService
  • ThreadPoolExecutor
  • FixedSizeThreadPoolExecutor
  • ScheduledThreadPoolExecutor
  • Semaphore
  • Binary Semaphore
  • BlockingQueue
  • DelayQueue
  • ConcurrentLinkedDeque
  • CountDownLatch
  • ForkJoinPool

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Python Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz