Why does Thread Class implements Runnable Interface [duplicate] - java

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.

Related

What is the function of this class? [duplicate]

This question already has answers here:
What is an interface in Java?
(13 answers)
Closed 3 years ago.
What does "implements Runnable" mean?
I am sending data from arduino to this java file
public static class SerialReader implements Runnable {
InputStream in;
public SerialReader( InputStream in ) {
this.in = in;
}
implements is a keyword in java for implementing an interface.
Acording to Oracle:
The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. The class must
define a method of no arguments called run.
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. Being active simply means that a
thread has been started and has not yet been stopped.
In addition, Runnable provides the means for a class to be active
while not subclassing Thread. A class that implements Runnable can run
without subclassing Thread by instantiating a Thread instance and
passing itself in as the target. In most cases, the Runnable interface
should be used if you are only planning to override the run() method
and no other Thread methods. This is important because classes should
not be subclassed unless the programmer intends on modifying or
enhancing the fundamental behavior of the class.
Source
implements is for implementing an interface.
and
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.

What is the preferred way to declare thread in java? [duplicate]

This question already has answers here:
"implements Runnable" vs "extends Thread" in Java
(42 answers)
Closed 7 years ago.
We can declare thread in class using two ways
extends Thread class
implements Runnable interface
so which scenario is the best way?
You should implement Runnable, since you can extend only one class, and you might want to use it to extend something that cannot be implemented.
There is no "best", they're both good. There is most appropriate, though.
For over 90% of the cases, implementing Runnable is the way to go.
You should never extend Thread, unless you need to change the functionality provided by the Thread class.

Scenario where extending thread is preferred than implement Runnable? [duplicate]

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

Thread object run method [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I need to write a program that uses multiple threads. I need to use the run() method after creating my thread objects. This run method seems to be built in. However, I need to write it and I need it to run a loop every time it is called. Can anyone help me understand how to do this?
You can create a new Thread instance by passing an anonymous implementation of the Runnable interface and then use the start() method to start the thread execution. See below:
Thread t = new Thread(new Runnable() {
public void run() {
while (!stopped) {
// do something interesting here
}
}
});
t.start();
Look at:
Counting Semaphores
http://tutorials.jenkov.com/java-concurrency/semaphores.html#counting
It's absolutely normal that the run() method is built into the Thread class. This class is meant to provide basic infrastructure for any class in your application that will represent a thread of execution. Think of Thread as 'any thread in the world'. Now the right way to use it in your application is to provide your own class that inherits Thread. This is done using extends keyword or using an anonymous class, like in Dan's answer. Let's assume you have extended the Thread class and called your class TaskToRunInParallel.
The documentation says that Thread class is special -- if you inherit it (like we just did) and put some code in the run() method of your own class (TaskToRunInParallel in our case), this code will be executed in parallel to the rest of the application. All you need to do is to call start() on the object of the class TaskToRunInParallel.
This is why the run() method is built-in: it provides you a prototype method to override in your own classes. This way any piece of code that works with Thread objects will be able to work with your TaskToRunInParallel objects, or any other class that inherits from Thread. Really: it is guaranteed that all of them will have run() method inherited from Thread and it's safe for that piece of code to call it. The result of this invocation will always be different though: each class inheriting from Thread may override run() in its own way. This is called polymorphism and together with inheritance is one of the cornerstones of object-oriented programming.
It's surprising how many concepts are involved when you think about overriding run() method of Thread class. Good luck.

Use of creating a Thread by extending a Thread class [duplicate]

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.

Categories