2348

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?

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
user65374
  • 24,139
  • 4
  • 19
  • 7
  • 66
    Thanks for this question, the answers cleared up a lot of misconceptions I had. I looked into the correct way to do Java threads before SO existed and there was a lot of misinformation/outdated information out there. – James McMahon May 08 '09 at 20:56
  • 5
    there is one reason you might want to extend Thread (*but I do not recommend it*), you can preemptively handle `interrupt()`. Again, it's an idea, it might be useful in the right case, however I do not recommend it. – bestsss Feb 12 '11 at 23:23
  • Please see also the answer, nicely explained: http://stackoverflow.com/q/5562720/285594 –  Apr 06 '11 at 10:06
  • @bestsss, I'm trying to puzzle out what you might mean about handling interrupt(). Are you trying to override the method? – Bob Cross Apr 25 '11 at 13:29
  • @Bob, yes bob. Java does that naturally for `java.nio.channels.InterruptibleChannel`(s) You can have a look at the impl. of Thread.interrupt(). Using a helping hand from the `interrupt()` caller is an idea and a useful approach, again not recommended for rookies. – bestsss Apr 27 '11 at 21:18
  • @Bob, there is another way to do it, by extending `java.nio.channels.spi.AbstractSelector` and override `wakeup()` but it's a way too dirty way to asses the case :) – bestsss Apr 27 '11 at 21:24
  • 8
    yes.As per the code,class Thread A can extend any class whereas class Thread B cant extend any other class – mani deepak Jan 27 '14 at 08:31
  • Should look at implementing a Callback over Runnable now. – RichieHH Jul 28 '14 at 03:48
  • @RichieHH - that depends. Callback only if you need a callback. That is, if the running code (the `Runnable` in OP) needs to execute logic in the caller. – ToolmakerSteve Sep 05 '15 at 11:59
  • Composition is preferred over Inheritance in Object oriented design – Peeyush Aug 13 '16 at 19:51
  • Dont use thread directly, you should use ExecutorService, which can be mocked for better tests – user1722245 Oct 19 '18 at 08:11
  • Extend Thread when you need to CHANGE the way Thread behaves. Implement runnable if you need to extend a different thread. If you need to share an object between threads, Runnable is the way to do, as thread doesnt allow it. If none of both cases apply, Runnable is more correct semantically speaking, although this last point is not very important, someone may think you've changed behaviour of thread if you extend it while you're not. – DGoiko Jul 21 '19 at 10:52

42 Answers42

1823

Yes: implements Runnable is the preferred way to do it, IMO. You're not really specialising the thread's behaviour. You're just giving it something to run. That means composition is the philosophically "purer" way to go.

In practical terms, it means you can implement Runnable and extend from another class as well... and you can also implement Runnable via a lambda expression as of Java 8.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 162
    Exactly, well put. What behavior are we trying to overwrite in Thread by extending it? I would argue most people are not trying to overwrite any behavior, but trying to use behavior of Thread. – hooknc Feb 12 '09 at 16:50
  • 94
    As a side comment, if you instantiate a Thread and do not call its start() method you are creating a memory leak in Java < 5 (this does not happen with Runnables): http://stackoverflow.com/questions/107823/why-is-my-java-program-leaking-memory-when-i-call-run-on-a-thread-object – Nacho Coloma Feb 07 '13 at 13:48
  • 26
    One minor advantage of Runnable is that, if in certain circumstances you don't care about, or don't want to use threading, and you just want to execute the code, you have the option to simply call run(). e.g. (very handwavy) `if (numberCores > 4) myExecutor.excute(myRunnable); else myRunnable.run()` – user949300 Mar 06 '13 at 19:30
  • 12
    @user949300 you can also do that with `extends Thread` and if you don't want threading why would you even implement `Runnable`... – m0skit0 Apr 23 '13 at 08:15
  • 5
    I would also add that by implementing Runnable now rather than extending Thread, you make it easy for a future refactor of using thread-pools, timers, schedulers, and Executors. – brettw Jul 18 '13 at 03:46
  • 32
    To paraphrase Sierra and Bates, a key benefit of implementing Runnable is that you are architecturally seperating the "job" from the "runner". – 8bitjunkie Feb 12 '14 at 09:28
  • 4
    Another addition to the "practical terms" bit: a `Runnable` is, really, an encapsulation of any bit of code. Under certain circumstances, it may be useful to run a `Runnable` even when not within the context of a new thread. – Isaac May 24 '14 at 01:35
  • 1
    @m0skit0 the point of the code by user949300 is that it uses a conditional to only enable multi-threading when there are enough physical core – lolski Aug 18 '14 at 15:34
  • @lolski My point being you can do that extending Thread or implementing Runnable, so really doesn't matter. – m0skit0 Aug 18 '14 at 15:56
  • 7
    @m0skit0: It doesn't matter if you don't care about your code expressing what you're interested in. Personally I care about that very much. Yes, you *can* extend `Thread` just to implement `Runnable`... heck, you can pass one `Thread` instance to the constructor of another `Thread` instance. That doesn't mean it's a good idea. – Jon Skeet Aug 18 '14 at 16:03
  • @JonSkeet Sorry, I didn't mean it doesn't matter to extend Thread or implement Runnable, I meant that that was not a valid argument for implementing Runnable :) – m0skit0 Aug 18 '14 at 17:15
  • 3
    @m0skit0: *What* wasn't a valid argument for implementing `Runnable`? You implement `Runnable` if you want to represent "something that can be run" - it doesn't necessarily have to be in a new thread. – Jon Skeet Aug 18 '14 at 17:32
  • 2
    Note that sometimes you (conceptually) *are* creating "runners", not "jobs". E.g. if you're writing a thread pool (for whatever reason). – user253751 Feb 12 '15 at 23:51
  • @JonSkeet i'm currently creating a class that handles Threads, for example: http://pastebin.com/QNc8xY46. is it OK, or terribly wrong to do so? – homerun Mar 03 '15 at 11:48
  • 7
    @somefolk: Well it feels terribly wrong to have public methods beginning with `_`, and having both `start()` and `_start()` is *really* confusing... as is having an instance method called `_sleep()`, when there's a static `sleep` method. Not that your `_sleep` method actually *does* anything with the instance anyway. In general, this looks like a bad idea to me so far. – Jon Skeet Mar 03 '15 at 11:50
  • The same answer is in official Java tutorials: https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html – greenmarker Jun 27 '15 at 18:02
  • A thread that performs a specific task "is a" thread in the object oriented Liskov substitution sense, so the philosophical argument is invalid. The valid arguments for preferring Runnable are practical, and have to do with modularization of code, especially in cases where you only want multithreading for performance reasons. – Warren Dew Oct 20 '15 at 16:35
  • I know this is an old post, but I feel maybe you could elaborate a little more @JonSkeet give code snippets, pros and cons. As I believe some other answers are more worthy! – Small Legend May 21 '16 at 14:31
  • 1
    @SmallLegend: I don't see any benefit in code snippets here - I've basically explained the philosophical difference. You should generally extend a class if you're planning to change some of the behaviour it implements. When you extend `Thread` *just* to override `Runnable`, you're changing behaviour that isn't part of `Thread` itself. – Jon Skeet May 21 '16 at 14:33
  • Okay, you know best! So generally, there are no situations where one would choose Thread over Runnable? @JonSkeet – Small Legend May 21 '16 at 14:36
  • 1
    @SmallLegend: Well if you were customising the actual threading behaviour you could, rather than just "the task that it's going to run". Not sure what custom threading behaviour you would implement, admittedly... – Jon Skeet May 21 '16 at 14:44
  • I think that composition being philosophically purer is an argument for extending an object. Since this answer is saying implementing Runnable is preferred to extending Thread, perhaps composition has nothing to do with the rationale. – H2ONaCl Oct 06 '16 at 22:48
  • 5
    @H2ONaCl No, absolutely the opposite. Preferring composition over inheritance speaks *against* extending anything. – Jon Skeet Oct 06 '16 at 22:57
  • Will there be any difference in the execution times between the two approaches? – AV94 Nov 18 '16 at 04:39
  • 2
    @AV94: Not measurable, I expect. – Jon Skeet Nov 18 '16 at 07:24
  • @JonSkeet: Since this is such a popular answer I think it would be a good idea to update it with best practices for the post Java 8 world: Often the best way is to pass a lambda expression to the `Thread` constructor: `new Thread(() -> { ... });` – Lii Oct 26 '20 at 12:50
  • 1
    @Lii: But the question isn't actually about "how to start a thread" - it's about the difference between `Runnable` and `Thread`. I'll add something saying you can also implement it via a lambda expression, but I don't want to go further than that. – Jon Skeet Oct 26 '20 at 14:01
  • 1
    Maybe it’s worth updating that creating a virtual thread will be impossible when subclassing `Thread`. So, for virtual threads, implementing `Runnable` will be the only way to go. – Holger Jun 16 '23 at 08:20
  • 1
    @Holger: I don't generally go over posts from 14 years ago for new features... otherwise that would basically be my whole life. I suggest you add that as a new answer. – Jon Skeet Jun 16 '23 at 08:21
  • 1
    I don’t want to add a new answer for what is just an addendum. But if you don’t mind I’d add this to your answer once virtual threads are released. – Holger Jun 16 '23 at 08:26
  • 1
    @Holger: Yes, feel free to add it to this answer if you want. – Jon Skeet Jun 16 '23 at 08:31
624

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 its 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());
cngzz1
  • 143
  • 2
  • 9
Bob Cross
  • 22,116
  • 12
  • 58
  • 95
  • 45
    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. – artbristol Nov 19 '12 at 11:27
  • 8
    @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...!* – Bob Cross Nov 19 '12 at 13:28
  • 7
    I know I'm a bit late commenting on this, but dealing with `FutureTask` directly is generally not what you want to do. `ExecutorService`s will create the appropriate `Future` for you when you `submit` a `Runnable`/`Callable` to them. Likewise for `ScheduledExecutorService`s and `ScheduledFuture` when you `schedule` a `Runnable`/`Callable`. – Powerlord Apr 28 '15 at 13:44
  • 3
    @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. – Bob Cross Apr 28 '15 at 17:04
  • in the first paragraph, you mentioned "if you use a Runnable and decide later on that this doesn't in fact require its own Thread, you can just call threadA.run()". Do you mean calling runnable.run()? Can you show some code your are referring to? – HKIT Jul 09 '22 at 09:53
  • 1
    @HKIT the question has been edited (several times) after this answer was posted. `threadA` used to be an instance of what is now called `MyRunnable` in the question. – Holger Jun 16 '23 at 08:19
292

Moral of the story:

Inherit only if you want to override some behavior.

Or rather it should be read as:

Inherit less, interface more.

spongebob
  • 8,370
  • 15
  • 50
  • 83
panzerschreck
  • 3,582
  • 2
  • 20
  • 29
  • 1
    This should always be the question if you start making a concurrent running Object! Do you even need the Thread Object funtions? – Liebertee Oct 21 '15 at 07:59
  • 7
    When inheriting from Thread, one nearly always wants to override the behavior of the `run()` method. – Warren Dew Jun 07 '16 at 04:01
  • 1
    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. – sura2k Jul 06 '16 at 09:28
  • 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. – peja Aug 30 '18 at 13:41
89

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.

Stuphan
  • 21
  • 7
Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76
89

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.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Herms
  • 37,540
  • 12
  • 78
  • 101
  • 8
    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`! – siegi Apr 26 '12 at 21:13
  • 9
    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. – Herms Apr 27 '12 at 13:19
85

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.

Saif
  • 6,804
  • 8
  • 40
  • 61
46

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.

Community
  • 1
  • 1
Fabian Steeg
  • 44,988
  • 7
  • 85
  • 112
  • 5
    I wouldn't think ExecutorService would be that useful if you just want to launch a single thread. – Powerlord Feb 12 '09 at 14:54
  • 1
    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. – Fabian Steeg Feb 12 '09 at 15:16
  • 4
    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. – zEro Jun 22 '13 at 21:16
  • 1
    @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. – Bodey Baker Dec 23 '13 at 15:07
35

I'm not an expert, but I can think of one reason to implement Runnable instead of extend Thread: Java only supports single inheritance, so you can only extend one class.

Edit: This originally said "Implementing an interface requires less resources." as well, but you need to create a new Thread instance either way, so this was wrong.

Powerlord
  • 87,612
  • 17
  • 125
  • 175
  • In runnable we can't make network calls, is it? As i am having android.os.NetworkOnMainThreadException. But by using thread i can make network calls. Please correct me if i am wrong. – Nabeel Thobani Oct 16 '14 at 05:16
  • @NabeelThobani Normal Java doesn't care, but it sounds like Android does. I'm not familiar enough with Android to say, though. – Powerlord Oct 16 '14 at 13:15
  • 1
    @NabeelThobani Of course you can. Probably you're not creating a Thread with your Runnable. – m0skit0 Jan 08 '15 at 19:11
21

I would say there is a third way:

public class Something {

    public void justAnotherMethod() { ... }

}

new Thread(new Runnable() {
   public void run() {
    instanceOfSomething.justAnotherMethod();
   }
}).start();

Maybe this is influenced a bit by my recent heavy usage of Javascript and Actionscript 3, but this way your class doesn't need to implement a pretty vague interface like Runnable.

Bart van Heukelom
  • 43,244
  • 59
  • 186
  • 301
  • 41
    This isn't really a third way. You're still implementing Runnable, just doing it anonymously. – Don Roby Jan 12 '11 at 18:50
  • 2
    @Don Roby: Which is different. It's often convenient, and you can use fields and final local variables from the containing class/method. – Bart van Heukelom Jan 13 '11 at 09:59
  • 7
    @BartvanHeukelom It's convenient, but not different. You can do this with any type of nested class, i.e. inner classes, local classes and lambda expressions. – xehpuk Jan 06 '15 at 01:28
20

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.

Alex - GlassEditor.com
  • 14,957
  • 5
  • 49
  • 49
18

Instantiating an interface gives a cleaner separation between your code and the implementation of threads, so I'd prefer to implement Runnable in this case.

starblue
  • 55,348
  • 14
  • 97
  • 151
17

Difference between Extending Thread and Implementing Runnable are:

enter image description here

Raman Gupta
  • 1,580
  • 15
  • 12
13

Everyone here seems to think that implementing Runnable is the way to go and I don't really disagree with them but there is also a case for extending Thread in my opinion, in fact you have sort of demonstrated it in your code.

If you implement Runnable then the class that implements Runnable has no control over the thread name, it is the calling code that can set the thread name, like so:

new Thread(myRunnable,"WhateverNameiFeelLike");

but if you extend Thread then you get to manage this within the class itself (just like in your example you name the thread 'ThreadB'). In this case you:

A) might give it a more useful name for debugging purposes

B) are forcing that that name be used for all instances of that class (unless you ignore the fact that it is a thread and do the above with it as if it is a Runnable but we are talking about convention here in any case so can ignore that possibility I feel).

You might even for example take a stack trace of its creation and use that as the thread name. This might seem odd but depending on how your code is structured it can be very useful for debugging purposes.

This might seem like a small thing but where you have a very complex application with a lot of threads and all of a sudden things 'have stopped' (either for reasons of deadlock or possibly because of a flaw in a network protocol which would be less obvious - or other endless reasons) then getting a stack dump from Java where all the threads are called 'Thread-1','Thread-2','Thread-3' is not always very useful (it depends on how your threads are structured and whether you can usefully tell which is which just by their stack trace - not always possible if you are using groups of multiple threads all running the same code).

Having said that you could of course also do the above in a generic way by creating an extension of the thread class which sets its name to a stack trace of its creation call and then use that with your Runnable implementations instead of the standard java Thread class (see below) but in addition to the stack trace there might be more context specific information that would be useful in the thread name for debugging (a reference to one of many queues or sockets it could processing for example in which case you might prefer to extend Thread specifically for that case so that you can have the compiler force you (or others using your libraries) to pass in certain info (e.g. the queue/socket in question) for use in the name).

Here's an example of the generic thread with the calling stack trace as its name:

public class DebuggableThread extends Thread {
    private static String getStackTrace(String name) {
        Throwable t= new Throwable("DebuggableThread-"+name);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(os);
        t.printStackTrace(ps);
        return os.toString();
    }

    public DebuggableThread(String name) {
        super(getStackTrace(name));
    }

    public static void main(String[] args) throws Exception {
        System.out.println(new Thread());
        System.out.println(new DebuggableThread("MainTest"));
    }
}

and here's a sample of the output comparing the two names:

Thread[Thread-1,5,main]
Thread[java.lang.Throwable: DebuggableThread-MainTest
    at DebuggableThread.getStackTrace(DebuggableThread.java:6)
    at DebuggableThread.<init>(DebuggableThread.java:14)
    at DebuggableThread.main(DebuggableThread.java:19)
,5,main]
AntonyM
  • 1,602
  • 12
  • 12
  • cHao what is your point? You could not use your code above during the execution of the thread to obtain a stacktrace of the threads creation (instead you would get a simple name or at best a stacktrace of the threads launch) but by subclassing thread you can do exactly that and force it, even requiring further context specific information thereby giving you a more concrete understanding of exactly which thread may be having an issue. – AntonyM Nov 02 '12 at 13:56
  • 8
    My point is that "If you implement Runnable then the class that implements Runnable has no control over the thread name..." is patently false. A class implementing `Runnable` can indeed control the thread name, as the thread running the code is by definition the current thread (and *any code that passes the security checks* has control over thread names). Considering you devote half your post to "omg, what about thread names!", that seems like a kinda big deal. – cHao Nov 02 '12 at 14:02
  • The thread name? Nothing is stopping you extending the thread class as well. – RichieHH Jul 28 '14 at 02:59
12

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.

Community
  • 1
  • 1
Jörg
  • 2,434
  • 23
  • 37
  • @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. – Jörg Apr 29 '16 at 10:15
12

Runnable because:

  • Leaves more flexibility for the Runnable implementation to extend another class
  • Separates the code from execution
  • Allows you to run your runnable from a Thread Pool, the event thread, or in any other way in the future.

Even if you don't need any of this now, you may in the future. Since there is no benefit to overriding Thread, Runnable is a better solution.

n13
  • 6,843
  • 53
  • 40
9

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.

Sionnach733
  • 4,686
  • 4
  • 36
  • 51
9

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.

Shababb Karim
  • 3,614
  • 1
  • 22
  • 35
6

Runnable is an interface, while Thread is a class which implements this interface. From a design point of view, there should be a clean separation between how a task is defined and between how it is executed. The former is the responsibility of a Runnalbe implementation, and the latter is job of the Thread class. In most of the cases implementing Runnable is the right way to follow.

developer110
  • 508
  • 6
  • 9
6

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.

didierc
  • 14,572
  • 3
  • 32
  • 52
6

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.

Nikhil A A
  • 441
  • 1
  • 4
  • 17
  • 1
    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. – Akash5288 Dec 04 '13 at 06:11
6

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

user2771655
  • 1,052
  • 3
  • 20
  • 38
6

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.

dharam
  • 7,882
  • 15
  • 65
  • 93
6

Separating the Thread class from the Runnable implementation also avoids potential synchronization problems between the thread and the run() method. A separate Runnable generally gives greater flexibility in the way that runnable code is referenced and executed.

Govula Srinivas
  • 173
  • 3
  • 10
6

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.

If you need some customization for this Thread API, you can extend Thread and modify implementation

Thread(ThreadGroup group, Runnable target, String name, long stackSize)

Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.

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

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
5

I find it is most useful to use Runnable for all the reasons mentioned, but sometimes I like to extend Thread so I can create my own thread stopping method and call it directly on the thread I have created.

5

Java does not support multiple inheritence so if you extends Thread class then no other class will be extended.

For Example: If you create an applet then it must extends Applet class so here the only way to create thread is by implementing Runnable interface

Himanshu Mohta
  • 1,033
  • 9
  • 15
5

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.

Rohit Chugh
  • 109
  • 1
  • 2
5

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 ");
        }
    } 
}
kinbiko
  • 2,066
  • 1
  • 28
  • 40
veritas
  • 2,444
  • 1
  • 21
  • 30
5

Yes, If you call ThreadA call , then not need to call the start method and run method is call after call the ThreadA class only. But If use the ThreadB call then need to necessary the start thread for call run method. If you have any more help, reply me.

Manoj Kumar
  • 587
  • 2
  • 9
  • 20
4

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.

Vishal
  • 816
  • 11
  • 19
4

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();
    }

}
JayC667
  • 2,418
  • 2
  • 17
  • 31
3

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
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

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 ==> Test1@396a51ab  --> 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.

slm
  • 15,396
  • 12
  • 109
  • 124
Arasn
  • 138
  • 10
2

This maybe isn't an answer but anyway; there is one more way to create threads:

Thread t = new Thread() {
    public void run() {
        // Code here
    }
}
AHugoH
  • 63
  • 1
  • 10
2

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.

Grim
  • 1,938
  • 10
  • 56
  • 123
2

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.

rashedcs
  • 3,588
  • 2
  • 39
  • 40
1

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.

Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
0

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

samkit shah
  • 657
  • 7
  • 18
0

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).

Pang
  • 9,564
  • 146
  • 81
  • 122
bharatj
  • 2,327
  • 1
  • 25
  • 25
0

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

Pen Lymeng
  • 271
  • 5
  • 14
0

If you want to separate your concerns like, if you want to create Tasks and it does not matter to you who is the worker working on your task then use Runnable and define your work as a task. Just like when you use executor service, you define tasks in form of Runnable/callable and give them to executor service which will then hold the responsibility of workers.

If you want to create a worker by yourself and assign that worker your task, you want more control over the worker thread then use Thread class.

Yogesh Sharma
  • 280
  • 1
  • 13
-1

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

    }

} 
Java Main
  • 1,521
  • 14
  • 18
  • I didn't downvote you but you have to create a Thread via `new Thread(new A())` and invoke `start()` method instead of `run()`. – statut Jul 07 '18 at 12:26