Related
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?
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.
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());
Moral of the story:
Inherit only if you want to override some behavior.
Or rather it should be read as:
Inherit less, interface more.
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.
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
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.
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.
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.
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.
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.
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.
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.
Difference between Extending Thread and Implementing Runnable are:
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]
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.
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.
If you are interested in this question, you might be also interested in the difference between Callable and Runnable.
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.
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.
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 :
If you don't have to extend Thread class and modify Thread API default implementation
If you are executing a fire and forget command
If You are already extending another class
Prefer "extends Thread" :
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
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.
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.
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:
thread handling in your application (ie. querying and modifying the execution context)
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.
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.
if you use runnable you can save the space to extend to any of your other class.
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.
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.
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.
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
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.
Adding my two cents here -
Always whenever possible use implements Runnable . Below are two caveats on why you should not use
extends Threads
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.
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 ");
}
}
}
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.
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?
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.
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());
Moral of the story:
Inherit only if you want to override some behavior.
Or rather it should be read as:
Inherit less, interface more.
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.
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
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.
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.
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.
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.
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.
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.
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.
Difference between Extending Thread and Implementing Runnable are:
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]
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.
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.
If you are interested in this question, you might be also interested in the difference between Callable and Runnable.
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.
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.
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 :
If you don't have to extend Thread class and modify Thread API default implementation
If you are executing a fire and forget command
If You are already extending another class
Prefer "extends Thread" :
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
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.
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.
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:
thread handling in your application (ie. querying and modifying the execution context)
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.
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.
if you use runnable you can save the space to extend to any of your other class.
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.
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.
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.
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
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.
Adding my two cents here -
Always whenever possible use implements Runnable . Below are two caveats on why you should not use
extends Threads
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.
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 ");
}
}
}
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.
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?
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.
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());
Moral of the story:
Inherit only if you want to override some behavior.
Or rather it should be read as:
Inherit less, interface more.
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.
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
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.
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.
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.
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.
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.
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.
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.
Difference between Extending Thread and Implementing Runnable are:
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]
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.
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.
If you are interested in this question, you might be also interested in the difference between Callable and Runnable.
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.
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.
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 :
If you don't have to extend Thread class and modify Thread API default implementation
If you are executing a fire and forget command
If You are already extending another class
Prefer "extends Thread" :
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
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.
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.
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:
thread handling in your application (ie. querying and modifying the execution context)
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.
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.
if you use runnable you can save the space to extend to any of your other class.
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.
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.
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.
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
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.
Adding my two cents here -
Always whenever possible use implements Runnable . Below are two caveats on why you should not use
extends Threads
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.
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 ");
}
}
}
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.
I was reading some articles on topic "implement runnable vs extend thread" and I do understand that implementing runnable is prefered because in Java you can't have multiple inheritance. I also read some article that said when you use run() method it just executes the code in current thread, and when you use start() it creates new thread which is I think better, but it depends. But I am still confused about, why you should implement Runnable in class? Why is that needed? Or extending Thread? You can create anonymous thread and start it without implementing runnable or anything.
Sample code of anonymous thread without implementing or extending
new Thread() {
public void run() {
System.out.print("Example");
}
}.start();
EDIT: After some answers and comments, I think what I did not understand was bit more clarified. I actually did not know the reason of implementing Runnable if its run method does not create new Thread. But many of you told me you can use something like this
new Thread(new Runnable())
So finally I want to know - This code up here, does it create a new Thread and executes the code inside the run method ?
Runnable or Callable is the preferred idiom
Pretty much always implement Runnable or Callable you should never in normal cases need to sub-class Thread directly.
If you do need specialized behavior of the Thread class, you either know what you are doing and why you need a different behavior for the Thread class for a good reason, or you are in way over your head.
Executors are the way to go
For most cases you should be using Executors and the plumbing around them instead of rolling your own when dealing with multiple Threads and their interactions and management.
You should never create a new Thread and manage its life-cycle anymore, error prone and hard to manage, lean on the Executors and leverage them.
why you should implement Runnable in class?
The only way to implement any interface is to define a class. Here are docs on Java interfaces.
Why is that needed? Or extending Thread?
You need to do one or the other if you want to use Thread directly. As others have pointed out, you should take a look at the ExecutorService classes which provide thread-pool support and hide the Thread stuff from the user. Here's the tutorial on the subject.
You can create anonymous thread and start it without implementing runnable or anything.
Your code is an anonymous class that extends Thread. As Ishtar provides, here are the docs about anonymous classes in case there is a question. If you looked at the .class files generated by the Java compiler from your code sample you would see something like Main.class and Main$1.class. Java is actually creating a class for you on the fly.
You could also so an anonymous class which implements Runnable:
new Thread(new Runnable() {
public void run() {
System.out.print("Example");
}
}).start();
But whether or not your use an anonymous class is orthogonal to the question of whether implementing Runnable or extending Thread is the better mechanism to define your thread task. For that question, as #MiserableVariable points out, Jon Skeet's answer is still very relevant.
When you deal with your own class hierarchy, you don't want to start from the Thread class in the first place. Thread class is an infrastructure for running your Runnables. And there is more, e.g. Executor, etc. Thread holds its state specific to its API. Runnable is a convenient (and a proper) way of wrapping your processing logic and isolate it from the surrounding it should be executed in.
It depends on your requirements, but in general it is a good idea to seperate What should be done? from Who does it?.
A Thread can execute code, but it has a lifecycle and once it finished you can't start the same Thread instance again.
A Runnable is just some code that can be executed or run(). The lifecycle of the object that implements Runnable is not necessarily bound to a thread's lifecycle and this gives you great benefit:
The same Runnable instance can be run multiple times. If you want to re-run a Runnable just create a Thread, pass the Runnable into the thread's constructor and call start().
Since a Runnable instance can be re-run easily the instance can remember the previous run's state.
The same Runnable instance can be run by multiple threads in parallel.
When you call run() method, it is method invocation on same thread rather than new thread. If you want something happen on separate thread, you either need to extend Thread (or) implement Runnable and call start() on thread object. Java thread life cycle may give you some clarity on difference between calling run() and start()
Quoting from the Oracle documentation on Concurrency.
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.
Note that the first idiom is Runnable and the second is extending from Thread. It looks like flexibility is the main motivator to go for implementing Runnable approach over extending Thread. I highly doubt if they both map to different implementations by the JVM (although I can't confirm it).
Anonymous classes are useful, but not applicable in most scenarios. This is as true for a Thread class, as for any other type of class.
In cases, for instance, that multiple instantiations of a Thread object are needed and that Thread object also has state (e.g., some calculation results), or communicates with other objects (e.g., via a queue), one has to extend the Thread class, or implementing the Runnable interface and then using a Thread constructor to actually start the thread.
The subject has been discussed extensively, so you can check the answers (and the links) posted to an earlier StackOverflow question, or many other similar ones.
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?
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.
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());
Moral of the story:
Inherit only if you want to override some behavior.
Or rather it should be read as:
Inherit less, interface more.
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.
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
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.
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.
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.
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.
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.
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.
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.
Difference between Extending Thread and Implementing Runnable are:
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]
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.
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.
If you are interested in this question, you might be also interested in the difference between Callable and Runnable.
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.
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.
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 :
If you don't have to extend Thread class and modify Thread API default implementation
If you are executing a fire and forget command
If You are already extending another class
Prefer "extends Thread" :
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
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.
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.
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:
thread handling in your application (ie. querying and modifying the execution context)
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.
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.
if you use runnable you can save the space to extend to any of your other class.
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.
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.
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.
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
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.
Adding my two cents here -
Always whenever possible use implements Runnable . Below are two caveats on why you should not use
extends Threads
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.
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 ");
}
}
}
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.