By user65374


2009-02-12 14:28:46 8 Comments

From what time I've spent with threads in Java, I've found these two ways to write threads:

With implements Runnable:

public class MyRunnable implements Runnable {
    public void run() {
        //Code
    }
}
//Started with a "new Thread(new MyRunnable()).start()" call

Or, with extends Thread:

public class MyThread extends Thread {
    public MyThread() {
        super("MyThread");
    }
    public void run() {
        //Code
    }
}
//Started with a "new MyThread().start()" call

Is there any significant difference in these two blocks of code ?

30 comments

@Rupesh Yadav 2013-03-05 14:26:04

Well so many good Answers, I want to add more on this. This will help to understand Extending v/s Implementing Thread.
Extends binds two class files very closely and can cause some pretty hard to deal with code.

Both approaches do the same job but there have been some differences.
The most common difference is

  1. When you extend Thread class, after that you can’t extend any other class which you required. (As you know, Java does not allow inheriting more than one class).
  2. When you implement Runnable, you can save space for your class to extend any other class in the future or now.

However, one significant difference between implementing Runnable and extending Thread is that
by extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same object instance.

The following example will help you to understand more clearly

//Implement Runnable Interface...
class ImplementsRunnable implements Runnable {

    private int counter = 0;

    public void run() {
        counter++;
        System.out.println("ImplementsRunnable : Counter : " + counter);
    }
}

//Extend Thread class...
class ExtendsThread extends Thread {

    private int counter = 0;

    public void run() {
        counter++;
        System.out.println("ExtendsThread : Counter : " + counter);
    }
}
    
//Use the above classes here in main to understand the differences more clearly...
public class ThreadVsRunnable {

    public static void main(String args[]) throws Exception {
        // Multiple threads share the same object.
        ImplementsRunnable rc = new ImplementsRunnable();
        Thread t1 = new Thread(rc);
        t1.start();
        Thread.sleep(1000); // Waiting for 1 second before starting next thread
        Thread t2 = new Thread(rc);
        t2.start();
        Thread.sleep(1000); // Waiting for 1 second before starting next thread
        Thread t3 = new Thread(rc);
        t3.start();

        // Creating new instance for every thread access.
        ExtendsThread tc1 = new ExtendsThread();
        tc1.start();
        Thread.sleep(1000); // Waiting for 1 second before starting next thread
        ExtendsThread tc2 = new ExtendsThread();
        tc2.start();
        Thread.sleep(1000); // Waiting for 1 second before starting next thread
        ExtendsThread tc3 = new ExtendsThread();
        tc3.start();
    }
}

Output of the above program.

ImplementsRunnable : Counter : 1
ImplementsRunnable : Counter : 2
ImplementsRunnable : Counter : 3
ExtendsThread : Counter : 1
ExtendsThread : Counter : 1
ExtendsThread : Counter : 1

In the Runnable interface approach, only one instance of a class is being created and it has been shared by different threads. So the value of counter is incremented for each and every thread access.

Whereas, Thread class approach, you must have to create separate instance for every thread access. Hence different memory is allocated for every class instances and each has separate counter, the value remains same, which means no increment will happen because none of the object reference is same.

When to use Runnable?
Use Runnable interface when you want to access the same resources from the group of threads. Avoid using Thread class here, because multiple objects creation consumes more memory and it becomes a big performance overhead.

A class that implements Runnable is not a thread and just a class. For a Runnable to become a Thread, You need to create an instance of Thread and passing itself in as the target.

In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.

When there is a need to extend a superclass, implementing the Runnable interface is more appropriate than using the Thread class. Because we can extend another class while implementing Runnable interface to make a thread.

I hope this will help!

@zEro 2013-06-10 06:25:08

Your code is patently wrong. I mean, it does what it does, but not what you intended to show.

@zEro 2013-06-10 06:31:25

To clarify: for the runnable case you've used the same ImplementsRunnable instance to start multiple threads, whereas for the Thread case you're creating different ExtendsThread instances which obviously leads to the behavior you showed. The 2nd half of your main method should be: ExtendsThread et = new ExtendsThread(); Thread tc1 = new Thread(et); tc1.start(); Thread.sleep(1000); Thread tc2 = new Thread(et); tc2.start(); Thread.sleep(1000); Thread tc3 = new Thread(et); tc3.start(); Is it any clearer?

@Rupesh Yadav 2013-06-10 10:19:01

@zEro Have to observed that in both case(implement Runnable & extend Thread), There are three independent threads & in case of extending Thread class each Thread of execution will use there own instance where as in implement Runnable all three threads use same instance to operate on. And, yes we can do it like this but we have more flexibility in case of Runnable.

@zEro 2013-06-10 12:29:17

I don't yet understand your intent, but my point was that if you create multiple instances of ExtendsThread -- they will all return 1 (as you've shown). You can get the same results for Runnable by doing the same thing there, i.e. creating multiple instances of ImplementsRunnable.

@Evil Washing Machine 2015-02-09 11:23:14

@zEro Hi, I'm from the future. Given that your version of the code has Thread incrementing as well, is the statement by extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same object instance then wrong? If not, then what is a case which demonstrates this?

@zEro 2015-02-09 12:14:01

@EvilWashingMachine please read all comments (and carefully)... I'm hoping people from the future are smarter than those of us who came before. ;-)

@Evil Washing Machine 2015-02-09 13:49:01

@zero unfortunately due to GM crops, declining test standards and global warming we in the future are really much more dumb than you guys are....I only see your 3 comments saying how Rupesh's sample doesn't prove his point, which I understand what the problem was, but nothing surrounding the statement he made nor a sample which shows this is the case. Of course you're not obligated to, but consider it a massive favour to us in the future? :)

@Evil Washing Machine 2015-02-09 13:56:19

(note I do know the object difference in thread and runnable, I've never seen it be an issue however)

@zEro 2015-05-18 20:07:41

@EvilWashingMachine: Been inactive for long.. and just saw this. I've added the object's hashcode to the print statements... + " hashcode: " + this.hashCode()

@zEro 2015-05-18 20:18:01

@EvilWashingMachine See the result here: goo.gl/ub2L8G You'll observe that with the ExtendsThread (ET), we are creating different threads as different objects (hint: hashcode) that are being run so counter for all of them is always initialized to zero and are then incremented to 1. Whereas, with ImplementsRunnable we are creating one ImplementsRunnable instance (that's the object; hint: hashcode) and we run it using 3 different threads.

@Evil Washing Machine 2015-05-19 16:30:22

@zEro thanks for returning, but I wasn't contending your comment...rather, I was asking if Rupesh's claim is true or false? In other words, if you extend Thread, do multiple instances of the Thread actually become different objects? Because I think this is wrong...

@zEro 2015-05-19 17:50:09

@EvilWashingMachine Note that Thread(Runnable r) is similar to Thread(ThreadGroup group, Runnable target, String name) This means that we are only setting the target of the thread, and the Thread's run method does nothing but to delegate to the target's run method - mentioned here

@zeal 2015-05-24 19:57:10

@zEro I am with you brother I get what you are saying. Since Thread class itself implements runnable interface, so any instance of a class extending the Thread class can be passed in to creating new Thread(et) in the running process i.e (as you rightly said) ExtendsThread et = new ExtendsThread(); Thread tc1 = new Thread(et); tc1.start(); Thread tc2 = new Thread(et); tc1.start(); now these two thread will share same instance i.e <et>, where as in this case not [please read the below comment for completion]

@zeal 2015-05-24 19:58:15

@zEro ` ExtendsThread tc1 = new ExtendsThread(); tc1.start(); Thread.sleep(1000); // Waiting for 1 second before starting next thread ExtendsThread tc2 = new ExtendsThread(); tc2.start(); `

@Nikos 2016-11-25 16:48:53

The code posted here is misleading and can lead to a headache. Thanks to @zEro for clearing it up a bit.

@slm 2019-10-27 14:15:15

@zEro - was this thread of comments addressed in this A'er? This A'er shows up on google and it would be nice if ppl didn't have to parse thru the comments to understand this critical aspect of the various approaches.

@Gerardo Cauich 2019-11-28 09:07:38

As @zEro mentioned. You can get the same behaviour of ExtendsThread if you create 3 instances of ImplementsRunnable so I think this is not a valid point. Downvoted.

@Arasn 2019-05-03 14:13:47

1. Extending the thread interface, is like you are making your class to behave as a thread only. Your new class will be like a enhanced thread.

jshell> public class Test extends Thread{
   ...> public Test(String name){
   ...> super(name);
   ...> }
   ...> public void run(){
   ...> System.out.println(Thread.currentThread().getName());
   ...> }
   ...> }
|  created class Test

jshell> Test t1=new Test("MyThread");
t1 ==> Thread[MyThread,5,main]

It creates a thread, not the Test object. So it's going to act like a single thread. You can not share the instance of Test class between threads.

2. Implementing the runnable interface.

jshell> public class Test1 implements Runnable{
   ...> public void run(){
   ...> System.out.println(Thread.currentThread().getName());
   ...> }
   ...> public String getName(){
   ...> return "testing";}
   ...> }
|  created class Test1

jshell> Test1 t1=new Test1();
t1 ==> [email protected]  --> this creates Test1 object.

This object can be shared across threads by,

jshell> Thread t1=new Thread(t1,"Hai");
t ==> Thread[Hai,5,main]

jshell> Thread t=new Thread(t1,"Hai");
t ==> Thread[Hai,5,main]

I think there's already been a lot that's been discussed on this topic, thought this might be helpful around the basics.

@Bob Cross 2009-02-12 14:37:05

tl;dr: implements Runnable is better. However, the caveat is important

In general, I would recommend using something like Runnable rather than Thread because it allows you to keep your work only loosely coupled with your choice of concurrency. For example, if you use a Runnable and decide later on that this doesn't in fact require it's own Thread, you can just call threadA.run().

Caveat: Around here, I strongly discourage the use of raw Threads. I much prefer the use of Callables and FutureTasks (From the javadoc: "A cancellable asynchronous computation"). The integration of timeouts, proper cancelling and the thread pooling of the modern concurrency support are all much more useful to me than piles of raw Threads.

Follow-up: there is a FutureTask constructor that allows you to use Runnables (if that's what you are most comfortable with) and still get the benefit of the modern concurrency tools. To quote the javadoc:

If you don't need a particular result, consider using constructions of the form:

Future<?> f = new FutureTask<Object>(runnable, null)

So, if we replace their runnable with your threadA, we get the following:

new FutureTask<Object>(threadA, null)

Another option that allows you to stay closer to Runnables is a ThreadPoolExecutor. You can use the execute method to pass in a Runnable to execute "the given task sometime in the future."

If you'd like to try using a thread pool, the code fragment above would become something like the following (using the Executors.newCachedThreadPool() factory method):

ExecutorService es = Executors.newCachedThreadPool();
es.execute(new ThreadA());

@artbristol 2012-11-19 11:27:01

This is better than the accepted answer IMHO. One thing: the snippet of code you have doesn't close down the executor and I see millions of questions where people get this wrong, creating a new Executor every time they want to spawn a task. es would be better as a static (or injected) field so it only gets created once.

@Bob Cross 2012-11-19 13:28:41

@artbristol, thanks! I don't disagree on the new Executor (we do what you suggest in our code). In writing the original answer, I was trying to write minimal code analagous to the original fragment. We have to hope that many readers of these answers use them as jumping off points. I'm not trying to write a replacement for the javadoc. I'm effectively writing marketing material for it: if you like this method, you should see all the other great things we have to offer...!

@Powerlord 2015-04-28 13:44:19

I know I'm a bit late commenting on this, but dealing with FutureTask directly is generally not what you want to do. ExecutorServices will create the appropriate Future for you when you submit a Runnable/Callable to them. Likewise for ScheduledExecutorServices and ScheduledFuture when you schedule a Runnable/Callable.

@Bob Cross 2015-04-28 17:04:01

@Powerlord, my intention was to make code fragments that matched the OP's as closely as possible. I agree that new FutureTask isn't optimal but it is clear for the purposes of explanation.

@Nidhish Krishnan 2013-05-11 08:59:42

If you want to implements or extends any other class then Runnable interface is most preferable, otherwise, if you do not want any other class to extend or implement then Thread class is preferable.

The most common difference is

enter image description here

When you extends Thread class, after that you can’t extend any other class which you required. (As you know, Java does not allow inheriting more than one class).

When you implements Runnable, you can save space for your class to extend any other class in the future or now.

  • Java doesn't support multiple inheritances, which means you can only extend one class in Java so once you extended Thread class you lost your chance and cannot extend or inherit another class in Java.

  • In Object-oriented programming, extending a class generally means, adding new functionality, and modifying or improving behaviors. If we are not making any modification on Thread then use Runnable interface instead.

  • Runnable interface represents a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is a good design decision.

  • Separating task as Runnable means we can reuse the task and also has the liberty to execute it from different means. since you can not restart a Thread once it completes. again Runnable vs Thread for task, Runnable is winner.

  • Java designer recognizes this and that's why Executors accept Runnable as Task and they have worker thread which executes those task.

  • Inheriting all Thread methods are additional overhead just for representing a Task which can be done easily with Runnable.

Courtesy from javarevisited.blogspot.com

These were some of the notable differences between Thread and Runnable in Java. If you know any other differences on Thread vs Runnable than please share it via comments. I personally use Runnable over Thread for this scenario and recommends to use Runnable or Callable interface based on your requirement.

However, the significant difference is.

When you extends Thread class, each of your thread creates a unique object and associate with it. When you implements Runnable, it shares the same object to multiple threads.

@Shababb Karim 2015-08-14 08:07:40

The simplest explanation would be by implementing Runnable we can assign the same object to multiple threads and each Thread shares the same object states and behavior.

For example, suppose there are two threads, thread1 puts an integer in an array and thread2 takes integers from the array when the array is filled up. Notice that in order for thread2 to work it needs to know the state of array, whether thread1 has filled it up or not.

Implementing Runnable lets you to have this flexibility to share the object whereas extends Thread makes you to create new objects for each threads therefore any update that is done by thread1 is lost to thread2.

@Pen Lymeng 2018-12-05 03:58:43

The main difference between Thread and Runnable is: - Thread is like: Worker (execute Runnable) - Runnable is like: Job (to be executed by Thread)

@bharatj 2018-09-02 10:02:50

I would say actual task is decoupled from the thread. We can pass around the task to Thread, Executor framework etc in case of Runnable, whereas with extending Thread task is coupled with thread object itself. The task isolation cannot be done in case of extending Thread. It's like we burn the task to Thread object just something like IC chip (and more specifically will not get any handle to task).

@Java Main 2018-04-25 20:21:53

You can use them jointly

Example :

public class A implements Runnable{

    @Override
    public void run() {


        while(true){
             System.out.println("Class A is running");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }}

    }

}



public class Test {

    public static void main(String[] args) {

        Thread myThread =new Thread(new A());// 1
        myThread.start();
        System.out.println(" executed after thread A");//will never be reached

    }

} 

@statut 2018-07-07 12:26:13

I didn't downvote you but you have to create a Thread via new Thread(new A()) and invoke start() method instead of run().

@Pritam Banerjee 2017-10-22 07:12:17

Thread class defines several methods that can be overriden by the the extending class. But to create a thread we must override the run() method. Same applies to Runnable as well.

However Runnable is a preferred method of creating a thread. The primary reasons are:

  1. Since Runnable is an interface, you can extend other classes. But if you extend Thread then that option is gone.

  2. If you are not modifying or enhancing a whole lot of Thread functionalities and extending the Thread class is not a preferred way.

@justcode 2018-02-15 11:25:11

Just complementing the Runnable by itself is not a thread is just a task that a thread can run.

@Raman Gupta 2017-10-01 15:05:06

Difference between Extending Thread and Implementing Runnable are:

enter image description here

@rashedcs 2017-04-23 05:14:01

By extending the thread class , the derived class can not extend any other base class because java only allow single inheritance. on the contrary, By implementing the runnable interface the class still extend other base class.

The most significant difference between implementing Runnable and extending Thread is given below :

By extending Thread, derived class itself is a thread object, whereas Implementing Runnable interface it shares the same object to multiple Threads.

@Grim 2016-11-10 07:05:51

In the rare case you only run it once, you should extend Thread because of DRY. If you call it multiple times, you should implement Runnable because the same thread should not be restarted.

@Herms 2009-02-12 14:51:35

One thing that I'm surprised hasn't been mentioned yet is that 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 (maybe to be run at a later time, but within the same thread). The options are a lot more open if you just use Runnable than if you bind yourself to Thread.

@siegi 2012-04-26 21:13:10

Well, you can actually do the same thing with a Thread object too because Thread implements Runnable… ;-) But it "feels better" doing this things with a Runnable than doing them with a Thread!

@Herms 2012-04-27 13:19:31

True, but Thread adds a lot of extra stuff that you don't need, and in many cases don't want. You're always better off implementing the interface that matches what you're actually doing.

@Saif 2015-05-12 13:50:15

Actually, It is not wise to compare Runnable and Thread with each other.

This two have a dependency and relationship in multi-threading just like Wheel and Engine relationship of motor vehicle.

I would say, there is only one way for multi-threading with two steps. Let me make my point.

Runnable:
When implementing interface Runnable it means you are creating something which is run able in a different thread. Now creating something which can run inside a thread (runnable inside a thread), doesn't mean to creating a Thread.
So the class MyRunnable is nothing but a ordinary class with a void run method. And it's objects will be some ordinary objects with only a method run which will execute normally when called. (unless we pass the object in a thread).

Thread:
class Thread, I would say A very special class with the capability of starting a new Thread which actually enables multi-threading through its start() method.

Why not wise to compare?
Because we need both of them for multi-threading.

For Multi-threading we need two things:

  • Something that can run inside a Thread (Runnable).
  • Something That can start a new Thread (Thread).

So technically and theoretically both of them is necessary to start a thread, one will run and one will make it run (Like Wheel and Engine of motor vehicle).

That's why you can not start a thread with MyRunnable you need to pass it to a instance of Thread.

But it is possible to create and run a thread only using class Thread because Class Thread implements Runnable so we all know Thread also is a Runnable inside.

Finally Thread and Runnable are complement to each other for multithreading not competitor or replacement.

@idelvall 2016-03-22 16:51:37

Exactly! This should be the accepted answer. BTW I think the question has been edited and ThreadA has no longer sense

@Saif 2016-03-22 17:10:13

the accepted answer is much more delegate thanks for you response @idelvall

@MichaelYe 2020-02-21 13:15:25

The best answer! Thanks!

@Fabian Steeg 2009-02-12 14:41:22

You should implement Runnable, but if you are running on Java 5 or higher, you should not start it with new Thread but use an ExecutorService instead. For details see: How to implement simple threading in Java.

@Powerlord 2009-02-12 14:54:07

I wouldn't think ExecutorService would be that useful if you just want to launch a single thread.

@Fabian Steeg 2009-02-12 15:16:08

From what I have learned one should no longer start a thread on your own in general, because leaving that to the executor service makes all much more controllable (like, waiting for the thread to suspend). Also, I don't see anything in the question that implies it's about a single thread.

@zEro 2013-06-22 21:16:03

What's the point of using any multi-threading if we know aprior that it's going to be a single thread. So let's assume we have multiple threads and this answer is valuable.

@porcoesphino 2013-12-23 15:07:51

@zEro I'm pretty sure there is a reason there is only one Event Dispatch Thread. I doubt it's the only case were it's best to have a separate thread but possibly not best to have multiple.

@JayC667 2016-04-24 11:41:51

The best way for most worker threads is to have the threading completely encapsuled in the worker class so that nothing can interfere from the outside and cause unwanted and invalid thread/class states.

I've just posted an example, so I'll also share this with you:

/**
 * This worker can only run once
 * @author JayC667
 */
public class ProperThreading {

    private final Thread        mThread         = new Thread(() -> runWorkingLoop());   // if you want worker to be able to run multiple times, move initialisation into startThread()
    private volatile boolean    mThreadStarted  = false;
    private volatile boolean    mStopRequested  = false;

    private final long          mLoopSleepTime;

    public ProperThreading(final long pLoopSleepTime /* pass more arguments here, store in members */ ) {
        mLoopSleepTime = pLoopSleepTime;
    }

    public synchronized void startThread() {
        if (mThreadStarted) throw new IllegalStateException("Worker Thread may only be started once and is already running!");
        mThreadStarted = true;
        mThread.start();
    }

    private void runWorkingLoop() {
        while (!mStopRequested /* && other checks */ ) {
            try {
                // do the magic work here
                Thread.sleep(mLoopSleepTime);

            } catch (final InterruptedException e) {
                break;
            } catch (final Exception e) {
                // do at least some basic handling here, you should NEVER ignore exception unless you know exactly what you're doing, and then it should be commented!
            }
        }
    }

    public synchronized void stopThread() {
        if (!mThreadStarted) throw new IllegalStateException("Worker Thread is not even running yet!");
        mStopRequested = true;
        mThread.interrupt();
    }

}

@Ravindra babu 2016-02-13 09:32:33

If I am not wrong, it's more or less similar to

What is the difference between an interface and abstract class?

extends establishes "Is A" relation & interface provides "Has a" capability.

Prefer implements Runnable :

  1. If you don't have to extend Thread class and modify Thread API default implementation
  2. If you are executing a fire and forget command
  3. If You are already extending another class

Prefer "extends Thread" :

  1. If you have to override any of these Thread methods as listed in oracle documentation page

Generally you don't need to override Thread behaviour. So implements Runnable is preferred for most of the times.

On a different note, using advanced ExecutorService or ThreadPoolExecutorService API provides more flexibility and control.

Have a look at this SE Question:

ExecutorService vs Casual Thread Spawner

@Alex - GlassEditor.com 2014-07-29 11:24:56

With the release of Java 8, there is now a third option.

Runnable is a functional interface, which means that instances of it can be created with lambda expressions or method references.

Your example can be replaced with:

new Thread(() -> { /* Code here */ }).start()

or if you want to use an ExecutorService and a method reference:

executor.execute(runner::run)

These are not only much shorter than your examples, but also come with many of the advantages stated in other answers of using Runnable over Thread, such as single responsibility and using composition because you're not specializing the thread's behaviour. This way also avoids creating an extra class if all you need is a Runnable as you do in your examples.

@ToolmakerSteve 2015-09-05 11:56:23

This answer needs explanation. After some puzzling, I conclude that () -> {} is supposed to represent the custom logic that someone needs? So it would be better said as () -> { /* Code here */ }?

@panzerschreck 2010-03-11 15:50:54

Moral of the story:

Inherit only if you want to override some behavior.

Or rather it should be read as:

Inherit less, interface more.

@Liebertee 2015-10-21 07:59:15

This should always be the question if you start making a concurrent running Object! Do you even need the Thread Object funtions?

@Warren Dew 2016-06-07 04:01:35

When inheriting from Thread, one nearly always wants to override the behavior of the run() method.

@sura2k 2016-07-06 09:28:09

You cannot override the behavior of a java.lang.Thread by overriding the run() method. In that case you need to override the start() method I guess. Normally you just reuse the behavior of the java.lang.Thread by injecting your execution block in to the run() method.

@peja 2018-08-30 13:41:17

The inheritance is not just for overriding some behavior, is also to use common behaviors. And it is the opposite, the more overrides, the worser hierarchy.

@Peter Lawrey 2015-07-26 18:01:29

Thread holds behaviour which is not intended to be accessed;

  • it's synchronized lock is used for join etc.
  • it has methods you can access by accident.

however if you sub-class Thread have to consider more Thread is implemented.

public class ThreadMain {
    public int getId() {
        return 12345678;
    }

    public String getName() {
        return "Hello World";
    }

    public String getState() {
        return "testing";
    }

    public void example() {
        new Thread() {
            @Override
            public void run() {
                System.out.println("id: "+getId()+", name: "+getName()+", state: "+getState());
            }
        }.start();
    }

    public static void main(String[] args) {
        new ThreadMain().example();
    }
}

If you run this you might expect

id: 12345678, name: Hello World, state: testing

however, you are not calling the methods you think you are because you are using the method in Thread not ThreadMain and instead you see something like

id: 11, name: Thread-0, state: RUNNABLE

@Vishal 2015-02-19 05:37:40

One difference between implementing Runnable and extending Thread is that by extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same object instance.

A class that implements Runnable is not a thread and just a class. For a Runnable to be executed by a Thread, you need to create an instance of Thread and pass the Runnable instance in as the target.

In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.

When there is a need to extend a superclass, implementing the Runnable interface is more appropriate than using the Thread class. Because we can extend another class while implementing Runnable interface to make a thread. But if we just extend the Thread class we can't inherit from any other class.

@veritas 2015-01-03 00:11:56

Adding my two cents here - Always whenever possible use implements Runnable . Below are two caveats on why you should not use extends Threads

  1. Ideally you should never extend the Thread class; the Thread class should be made final. At least its methods like thread.getId(). See this discussion for a bug related to extending Threads.

  2. Those who like to solve puzzles can see another side effect of extending Thread. The below code will print unreachable code when nobody is notifying them.

Please see http://pastebin.com/BjKNNs2G.

public class WaitPuzzle {

    public static void main(String[] args) throws InterruptedException {
        DoNothing doNothing = new DoNothing();
        new WaitForever(doNothing).start();
        new WaitForever(doNothing).start();
        new WaitForever(doNothing).start();
        Thread.sleep(100);
        doNothing.start();
        while(true) {
            Thread.sleep(10);
        }
    }


    static class WaitForever extends  Thread {

        private DoNothing doNothing;

        public WaitForever(DoNothing doNothing) {
            this.doNothing =  doNothing;
        }

        @Override
        public void run() {
            synchronized (doNothing) {
                try {
                    doNothing.wait(); // will wait forever here as nobody notifies here
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Unreachable Code");
            }
        }
    }

    static class DoNothing extends Thread {

        @Override
        public void run() {
            System.out.println("Do Nothing ");
        }
    } 
}

@Jörg 2014-02-13 09:07:11

Since this is a very popular topic and the good answers are spread all over and dealt with in great depth, I felt it is justifiable to compile the good answers from the others into a more concise form, so newcomers have an easy overview upfront:

  1. You usually extend a class to add or modify functionality. So, if you don't want to overwrite any Thread behavior, then use Runnable.

  2. In the same light, if you don't need to inherit thread methods, you can do without that overhead by using Runnable.

  3. Single inheritance: If you extend Thread you cannot extend from any other class, so if that is what you need to do, you have to use Runnable.

  4. It is good design to separate domain logic from technical means, in that sense it is better to have a Runnable task isolating your task from your runner.

  5. You can execute the same Runnable object multiple times, a Thread object, however, can only be started once. (Maybe the reason, why Executors do accept Runnables, but not Threads.)

  6. If you develop your task as Runnable, you have all flexibility how to use it now and in the future. You can have it run concurrently via Executors but also via Thread. And you still could also use/call it non-concurrently within the same thread just as any other ordinary type/object.

  7. This makes it also easier to separate task-logic and concurrency aspects in your unit tests.

  8. If you are interested in this question, you might be also interested in the difference between Callable and Runnable.

@Jörg 2016-04-29 10:15:59

@Pino Yes, Thread itself is also a Runnable. However, if you extend it to just use it as a Runnable, what's the point? Why not just use a plain Runnable without all the baggage. So, I'd argue, that if you extend Thread, you also would execute it by using its start method, which can only be used once. That's the point Nidhish-Krishnan wanted to make in his answer. Note, that mine is just a compilation or brief summary of other answers here.

@samkit shah 2014-06-18 07:22:39

Simple way to say is: If you implement interface that means you are implementing all methods of it and if you extending the class you are inheriting method of your choice... In this case,there is only a one method named Run() so better to implement Runnable interface..

@Rohit Chugh 2014-03-05 06:13:58

Difference between Thread and runnable .If we are creating Thread using Thread class then Number of thread equal to number of object we created . If we are creating thread by implementing the runnable interface then we can use single object for creating multiple thread.So single object is shared by multiple Thread.So it will take less memory

So depending upon the requirement if our data is not senstive. So It can be shared between multiple Thread we can used Runnable interface.

@Sionnach733 2014-01-21 16:44:09

This is discussed in Oracle's Defining and Starting a Thread tutorial:

Which of these idioms should you use? The first idiom, which employs a Runnable object, is more general, because the Runnable object can subclass a class other than Thread. The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread. This lesson focuses on the first approach, which separates the Runnable task from the Thread object that executes the task. Not only is this approach more flexible, but it is applicable to the high-level thread management APIs covered later.

In other words, implementing Runnable will work in scenarios where your class extends a class other than Thread. Java does not support multiple inheritance. Also, extending Thread will not be possible when using some of the high-level thread management APIs. The only scenario where extending Thread is preferable is in a small application that won't be subject to updates in future. It is almost always better to implement Runnable as it is more flexible as your project grows. A design change won't have a major impact as you can implement many interfaces in java, but only extend one class.

@dharam 2013-11-22 03:11:51

Can we re-visit the basic reason we wanted our class to behave as a Thread? There is no reason at all, we just wanted to execute a task, most likely in an asynchronous mode, which precisely means that the execution of the task must branch from our main thread and the main thread if finishes early, may or may not wait for the branched path(task).

If this is the whole purpose, then where do I see the need of a specialized Thread. This can be accomplished by picking up a RAW Thread from the System's Thread Pool and assigning it our task (may be an instance of our class) and that is it.

So let us obey the OOPs concept and write a class of the type we need. There are many ways to do things, doing it in the right way matters.

We need a task, so write a task definition which can be run on a Thread. So use Runnable.

Always remember implements is specially used to impart a behaviour and extends is used to impart a feature/property.

We do not want the thread's property, instead we want our class to behave as a task which can be run.

@user2771655 2013-09-26 05:58:02

if you use runnable you can save the space to extend to any of your other class.

@Nikhil A A 2013-07-25 17:29:00

One reason you'd want to implement an interface rather than extend a base class is that you are already extending some other class. You can only extend one class, but you can implement any number of interfaces.

If you extend Thread, you're basically preventing your logic to be executed by any other thread than 'this'. If you only want some thread to execute your logic, it's better to just implement Runnable.

@Akash5288 2013-12-04 06:11:04

Yes by implementing Runnable interface to are free to implement your own logic by extending any class, thats why Runnable is mostly preferred over Thread class.

@didierc 2013-03-18 10:14:31

That's the S of SOLID: Single responsibility.

A thread embodies the running context (as in execution context: stack frame, thread id, etc.) of the asynchronous execution of a piece of code. That piece of code ideally should be the same implementation, whether synchronous or asynchronous.

If you bundle them together in one implementation, you give the resulting object two unrelated causes of change:

  1. thread handling in your application (ie. querying and modifying the execution context)
  2. algorithm implemented by the piece of code (the runnable part)

If the language you use supports partial classes or multiple inheritance, then you can segregate each cause in its own super class, but it boils down to the same as composing the two objects, since their feature sets don't overlap. That's for the theory.

In practice, generally speaking, a programme does not need to carry more complexity than necessary. If you have one thread working on a specific task, without ever changing that task, there is probably no point in making the tasks separate classes, and your code remains simpler.

In the context of Java, since the facility is already there, it is probably easier to start directly with stand alone Runnable classes, and pass their instances to Thread (or Executor) instances. Once used to that pattern, it is not harder to use (or even read) than the simple runnable thread case.

Related Questions

Sponsored Content

88 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

35 Answered Questions

[SOLVED] What is the difference between a process and a thread?

33 Answered Questions

[SOLVED] When to use LinkedList over ArrayList in Java?

58 Answered Questions

[SOLVED] How to create a memory leak in Java?

66 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 4112864 View
  • 3550 Score
  • 66 Answer
  • Tags:   java random integer

44 Answered Questions

[SOLVED] Can't start Eclipse - Java was started but returned exit code=13

19 Answered Questions

59 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

35 Answered Questions

Sponsored Content