I suggest not calling your Runnable "ThreadA". It is not a thread - it is a piece of code that can be executed by thread.
–
DJClayworthFeb 12 '09 at 15:06

13

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 McMahonMay 8 '09 at 20:56

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.
–
bestsssFeb 12 '11 at 23:23

29 Answers
29

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.

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.
–
hookncFeb 12 '09 at 16:50

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()
–
user949300Mar 6 '13 at 19:30

2

@user949300 you can also do that with extends Thread and if you don't want threading why would you even implement Runnable...
–
m0skit0Apr 23 '13 at 8:15

3

To paraphrase Sierra and Bates, a key benefit of implementing Runnable is that you are architecturally seperating the "job" from the "runner".
–
7SpecialGemsFeb 12 '14 at 9:28

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

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.
–
artbristolNov 19 '12 at 11:27

2

@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 CrossNov 19 '12 at 13:28

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

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 a space for your class to extend any other class in future or now.

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

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

Your code is patently wrong. I mean, it does what it does, but not what you intended to show.
–
zEroJun 10 '13 at 6:25

9

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?
–
zEroJun 10 '13 at 6:31

@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.
–
Rupesh YadavJun 10 '13 at 10:19

8

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.
–
zEroJun 10 '13 at 12:29

@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?
–
Evil Washing MachineFeb 9 at 11:23

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

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!
–
siegiApr 26 '12 at 21:13

2

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.
–
HermsApr 27 '12 at 13:19

I wouldn't think ExecutorService would be that useful if you just want to launch a single thread.
–
PowerlordFeb 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 SteegFeb 12 '09 at 15:16

2

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.
–
zEroJun 22 '13 at 21:16

@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.
–
porcoesphinoDec 23 '13 at 15:07

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

The most common difference is

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 a space for your class to extend any other class in future or now.

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

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

Runnable interface represent 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 good design decision.

Separating task as Runnable means we can reuse the task and also has 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 can be done easily with Runnable.

These were some of notable difference 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 unique object and associate with it.
When you implements Runnable, it shares the same object to multiple threads.

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 ThobaniOct 16 '14 at 5:16

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:

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.
–
AntonyMNov 2 '12 at 13:56

6

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.
–
cHaoNov 2 '12 at 14:02

The thread name? Nothing is stopping you extending the thread class as well.
–
RichieHHJul 28 '14 at 2:59

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:

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

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

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.

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.

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

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.

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

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.

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.

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:

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.

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.

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.

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.

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.

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post.
–
winterbloodAug 20 '14 at 22:11

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.

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.

Runnable is a FunctionalInterface, which means that it can be created with lambda expressions or method references.

Your example can be replaced with:

new Thread(() -> {}).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.

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

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 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. But if we just extend the Thread class we can't inherit from any other class.