This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: “implements Runnable” vs. “extends Thread”
Java provides two options to create a Thread class i.e either by implementing Runnable or by extending Thread class.
I know there can be many reasons to implement a Runnable but not sure where the scenario would be to extend a Thread class to create own Thread class?
Could you please provide me scenarios where extending Thread seems to be feasible or better option or advantageous...
There was a
Question on the threads but that did'nt answer my question
There is almost no reason to extend Thread, basically the only reason you would want to extend thread is if you were going to override things other than run() which is generally a bad idea. The reason it is less common to extend Thread is because then the class can't extend anything else, and if you're only overriding the run() method, then it would be kinda pointless to extend Thread and not implement Runnable.
Runnable is an interface with just one method run() that needs to be implemented by the class implementing the interface.
e.g.
public class MyRunnable implements Runnable {
#Override
public void run() {
//...
}
}
MyRunnable is not a Thread nor can you create a new thread just by using that class. So, it doesn't quite make sense to say -
Java provides two options to create a Thread class i.e either by implementing Runnable ...
You can extend the Thread class but just like #John said there isn't any point in doing so.
But if you want to execute some code in a new thread then the following is the best way -
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
t.start() method starts a new thread and invokes run() method on r (which is an instance of MyRunnable.
Related
This question already has answers here:
Why does Thread implement Runnable?
(2 answers)
Closed 5 years ago.
First of all i have gone through similar question but couldn't get my answer, like -
Why does Thread implement Runnable?
So my question is that Runnable contains only run method which is there is Thread class itself then why does Thread Class implements Runnable Interface and what functionalities does implementing Runnable provides to Thread class, what will happen if Thread class does not implements Runnable.
"The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. [...]
This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread."
oracle doc
But I think what your exactly looking for is here. The answer given was "backward compability".
Sometimes Java needs to make choices, and they always chose solutions dealing with backward compability.
If Thread class doesn't implement Runnable then Thread class will not have run method. Then jvm will not treat it as a thread at all.
Is it a kind of bad design to use local Thread field in Runnable implemented class like this:
public class TestingThread implements Runnable {
Thread t;
public TestingThread() {
t = new Thread(this, "Testing thread");
}
public void start()
{
t.start();
}
...
Although this kind of question is obviously opinionated, I will tell you why I think that this is a design flaw. (Actually, I provoked this question, so maybe I should answer.)
A Runnable is an object holding the code that will (or should) be executed within a thread. The documentation explains it this way:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
The main idea behind the Runnable interface is to separate the executable code from the means of executing it. There are several possibilities of running such code in an own thread.
One of those possibilities is the Thread class. From its documentation:
There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started. [...] The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started.
In my opinion, you always should do the latter. Define implementations of the Runnable interface, pass instances of them to the constructor of a Thread, then start the thread. Example:
class MyRunnable implements Runnable { ... }
void runMyCodeInOwnThread() {
Runnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
The other way of executing a Runnable in a thread is an Executor, although you most likely will use an ExecutorService (actually a subtype of Executor). The utility class Executors will most likely be used for retrieving an executor service. Example:
class MyRunnable implements Runnable { ... }
void runMyCodeInOwnThread() {
Runnable runnable = new MyRunnable();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(runnable); // or simply "executor.execut(runnable);"
}
If you don't tangle your runnable with the means of how to execute it, you are free to use either mechanism or change it in the future when requirements advance.
However, as I looked through the classes' documentations, I also saw the same mechanism in the examples. Still, I think this is not a good design.
Keeping or using a local thread variable inside another thread class is matter of choice.But personally from my knowledge its not a good design,until you have specific requirement to do so and use that local thread variable inside your thread class.You hardly needs this type of requirement in real life scenario.Hope it helps you !
This question already has answers here:
"implements Runnable" vs "extends Thread" in Java
(42 answers)
Closed 8 years ago.
As a beginner, I was reading about 2 ways of implementing Multithreading in Java.
I read this thread on SO and on many other threads.
It is stated that
"prefer runnable" , extends thread only when you are specialising Thread's behaviour.
Can someone explain me what is meant by specializing Thread behaviour by providing me a small piece of snippet which help me understand this line.
You should extend a Thread as much as you extend other library classes.
Take a List for example, more specifically ArrayList, you could add extra behaviour on it, like rejecting a value when adding if a certain predicate fails.
Then you can call that an PredicatedArrayList.
It is still a debate whether you want to extend ArrayList here or not, but that debate is not up for this question.
So an example of extending a thread would be a thread that kills itself after a specific amount of time. Then you would have SuicidingThread extends Thread, which could have a constructor taking the time.
This even fortifies the argument that you should put your actual tasks in a Runnable.
Like Runnable somethingRunnable = new SomeClass();, where SomeClass implements Runnable.
Now you can do either:
Thread someThread = new Thread(somethingRunnable);
Thread someThread = new SuicidingThread(somethingRunnable, 5, TimeUnit.DAYS);
So this would be an usecase for extending thread.
Specializing means, extend the functionality of existing Thread class. It could be anything depending on the application requirement. The one I've mentioned below may not be true logically.
public class MyThread extends Thread{
#Override
public void interrupt() {
if(thread has started some operation on database){
//roll back transaction
}
super.interrupt();
}
}
Here before interrupting the thread, we can check if any database operation is running currently and roll back it. Though it can be done from the interrupted catch block, handling it from extended class reduce the number of lines if you create lots of instances of this thread at different places in the application. It's just an example, nobody will use it this way. :)
Because java does not support for multi-inheritance.
If you have a class named Person.
class Person{
String name;
int age;
}
Then you want to create a class Man which extends Person
class Man extends Person{
}
Now you have used the extends keyword to declare that Man is a Person. Then if you want a Man to be performed like a thread,you can not extend Thread again because Java do not support for multi-inheritance.So just use Runnable interface which can be implements together with other interfaces.
class Man extends Person implements Runnable{
public void run()[
}
}
EDIT:
"extends thread only when you are specialising Thread's behaviour" means that your class is only a Thread which does not have other features,because when your class contains other features,you need to extends other super classed rather then the Thread class.As I have mentioned before,java does not support for multi-inheritance,so just extends thread only when you are specialising Thread's behaviour.
Java doesn't support multiple inheritance, which means you can only extend one class in Java so once you extended Thread class you lost your chance and can not extend or inherit another class in Java so this class is specialized for Thread only.
By extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same runnable instance.
Extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread then use Runnable interface instead.
Thread class has some behavior decided by JDK developers when you want to make some modification to it then you can extend your class with Thread class and modify it.
There are several reasons for preferring Runnable implementation over Thread extension:
Always prefer composition over inheritance and you will end up with less coupled code.
One way to decide how your class is related to Thread is to check the "is a" relation vs a "has a".
In practice extending Thread will force you to create new instances instances of your class for each thread, instead of sharing the same instance in the case of Runnable. See this.
Java supports only single inheritance
One example of legit use cases for extending Thread is when you need to design a Thread class with custom properties (ex: caching resources) that is being part of a CachedThreadPool
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: “implements Runnable” vs. “extends Thread”
I have two questions about multithreaded programming. I read a few answers on the internet, but still I can't find a satisfying answer.
Implementing the Runnable is preferred over extending the thread class. Why?
How is it that we are able to get away with overriding just the run() method?
According to 'The Complete Reference to Java' by Herbert Schildt, If we are not overriding any methods of Thread class other than run(), it's better we implement Runnable.
My 2nd question might sound a bit silly, but I seem to be missing something and I'm not sure about how the whole thing works.
1: Implementing the Runnable is preferred over extending the thread class. why?
Because it allows your class to extend another class if it wants to instead of being forced to extend Thread.
2: How is it that we are able to get away with over-ridding just the run() method?
You can certainly override other methods but the Thread object will call the run() method when the thread is started. That's how it works. The default Thread.run() method is:
public void run() {
if (target != null) {
target.run();
}
}
If you call the Thread constructor with a Runnable then that is what the target is set to. If you instead extend Thread and #Override the run() method then that is the method that will be called when the thread object is started.
That's how the Thread class works.
2: How is it that we are able to get away with over-ridding just the run() method?
You may have misspoke here and were instead asking why we only need to implement the run() method in Runnable().
Runnable is an interface with a single run() method that you must implement.
Thread is a concrete class that you are extending. You can override any methods in a concrete class unless the class is final or the method is final.
Make sure you use proper Java terminology and don't mixup implement and override.
Three fundamentals before you delve deeper.
A class can only extend one class.
A class can implement any number of interfaces.
An interface can extend any number of interfaces.
Additionally, an abstract class is a class. So it behaves like a class and you can't implement it. You only extend it.
There are a number of traps which can occur if you extend Thread which you don't get with implementing Runnable.
public static String getName() {
return "My Test Application";
}
public static void stop() {
System.out.println("Shutting down");
}
public static void main(String... args) {
new Thread() {
#Override
public void run() {
System.out.println(getName());
stop();
}
}.run();
System.out.println("Bye now.");
}
prints
Thread-0
Bye now.
See how many bugs you can spot.
Unnecessary inheritance is generally a bad idea. You might hear "prefer composition over inheritance" often enough. I'm sure google can pull up enough links for you. The general issue is that inheritance bring tight, unnecessary coupling between classes.
Same goes for GUI components, btw.
I wanted to write multiple threads under one class and found one way of doing it.
public class ThreadExample {
public static void main(String[] arg)
{
Thread one = new Thread() {
public void run() {
try {
Thread.sleep(2000);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("One");
}
};
Thread two = new Thread() {
public void run() {
System.out.println("Two");
}
};
one.start();
two.start();
}
}
Thing I don't get here is, I am neither extending the Thread class nor am I implementing the Runnable interface. How do I understand this?
And If the answer is, "I am just creating the object of the Thread class and using it, then why not always do this rather than doing the things mentioned above?
Technically, what you are doing is extending Thread. You are extending it on the fly with something called an anonymous inner class - to learn more about what that is, start here and read this page plus the next two.
What this means is you are creating temporary inline subclasses that have no name, and whose definitions survive only until the method finishes. Why do this rather than create a named subclass of Thread or implementation of Runnable? It makes sense when the body of run() is as simple as the examples above - there's less typing and fewer .java files to keep track of. One-off simple tasks like these are good candidates for anonymous inner class extension of Thread. For major program logic, you probably want to do a full named class implementation in a separate file.
In addition, once you've gotten good experience with Thread, I would encourage you to check out the java.util.concurrent package.
Ah, but you are extending the Thread class... anonymously.
When using the new Class() {} syntax, you are creating an anonymous class that is a sub-class (ie effectively extends) of the named class.
In this case, you have overridden the Thread.run() method.
This approach, while it works, it not considered "good design", because you are extending Thread, but you are not creating a new kind of Thread. It is better to pass a Runnable into the constructor:
new Thread( new Runnable() {
public void run() {
// do something
}
}).start();
Bohemian answered your first question so I'll answer your second one: "I am just creating the object of the Thread class and using it, then why not always do this rather than doing the things mentioned above?"
If you always do it the way you did in your question then you can't separate the logic that performs the task from the way the task is run. Implementing runnable lets you bundle the logic that performs your task separately from the code that manages how your task is run.
If you use runnables you are able to run your task in a new thread, run your task in the calling thread, run your task after some delay or run it in some other fashion without modifying the code in the runnable.
When working with threads you'll generally want to use an ExecutorService instead of using the thread class directly. Executor services provide facilities for limiting the numbers of threads, handling failed executions, determining when a runnable completes, getting return values from tasks run in other threads and so on.