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.
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.
This question already has answers here:
Inheritance in java and Superclasses(Object, Class)
(7 answers)
Closed 7 years ago.
In Java, they say that Multiple Inheritance is not supported. Also its a fact, that each class in Java extends class Object. So if I write :
public class ThreadInstance extends Thread {
}
How does this compile? ThreadInstance here is actually extending Thread as well as Object. Isn't it multiple Inheritance here.
By multiple inheritance you should understand inheriting multiple classes at the same time, e.g. it's impossible to create a
public class ThreadInstance extends Thread, Object {
}
because class hierarchy would look like this:
ThreadInstance
^ ^
Thread Object
When you define your ThreadInstance like you did, the ThreadInstance inherits Object too, but it first inherits thread.
ThreadInstance
^
Thread
^
Object
There is no multiple inheritance there.
Your class extends Thread but Thread already extends Object so it's still single-inheritance as it follows the same line of inheritance
Object is implicitly inherited by every class. In your ThreadInstance class, Thread is explicitly inherited.
Thus every Java class except Object must have a super-class. There's nothing all to special about implicit inheritance, it's simply there to reduce boilerplate code.
Your class that extends that other class, but it extends Object, too, so you're still in one line of inheritance, not two.
Eg.
ThreadInstance extends Thread, but Thread in turn extends Object so cant I say ThreadInstance extends Object.
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
I always wonder how just by implementing an interface , sub class acquires the behavior. For example if I implement Runnable interface my subclass start behaving as thread, but what if I implement all the methods defined in interface Runnable but not write "implementing Runnable", subclass doesn't behave as Thread. Same with EventListeners . Please help me understanding this behavior.
By implementing an interface I, you're declaring that the Object "is a" I and that it'll contain all the methods defined by this interface. If you just implement the methods of the interface I, but don't declare it by an implement statement, compiler won't be able to determine that your class "is a" I and you won't be able to use it as a I-type.
No, Runnable has nothing to do with behaving like a thread. It just contains a plain, simple, void nullary method called "run".
Not specifying implements Runnable will just make your object not an instance of the Runnable type, which means you won't be able to pass it to a method requiring a Runnable. This is just an issue of type safety. The method you call could also accept an Object and invoke run using reflection, with the exact same behavior.
When you are implementing Runnable your class does not become thread and does not start behavior as thread. However if your class implements Runnable you can run it in context of thread:
class MyClass1 implements Runnable {
public void run() {
// this stuff will run in thread when thread's start() method is called
}
}
new Thread(new MyClass1()).start();
But java is strongly typed language. You can just create class like this:
class MyClass2 {
public void run() {
// this stuff will run in thread when thread's start() method is called
}
}
But it will not be Runnable. Therefore you cannot just send it to thread:
new Thread(new MyClass2()).start();
In this case you will get compilation error. Compiler cannot know that your class indeed implements method that looks like one that is declared in Runnable. You must declare this (as in first case).
A Runnable only allows your class to be run in a Thread. You still need e.g. a java.util.concurrent.Executor to actually run it in an actual Thread.
However, you can extend Thread which would allow you to call Thread.start().
To actually get out behavior from just implementing an interface, you would need a second object inspecting the classpath for classes implementing your interface using reflection, and then do something with that class.
Your question has two aspect:
Interface as a contract: Interfaces imposes a behavioral contract on a class implementing it. For example, If Car is an interface with some methods abstractly defining a car, any class implementing Car interface will have to define the methods of the car. You are free to actually implement the behavior.
Analogy of Runnable acting as thread is incorrect. What makes Runnable class act as thread is the the Thread class. Runnable just specifies the contract for a class to act as thread. Check this post.
This is not a subclassing behavior. In order to use subclass behavior you need to extend the class.
W.r.t interfaces these are just templates/contracts that are implemented by class. In order for runnable to work calling program need to instantiate a thread and when thread will start it will call run method implemented by your class.
I always wonder how just by implementing an interface , sub class acquires the behavior.
It doesn't 'acquire' any 'behaviour'. The subclass provides the behaviour. What implementing the interface does is provide the compile-time type signatures such that you can use the subclass where the interface is specified.
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.