Always prefer the Runnable
however when you want to modify some non-final methods then use Thread class
because Runnable interface has only abstract run () method.
Key
Points:
Multiple
inheritance is not allowed in java: By implementing
Runnable, still a option left to extending some other class. So, it’s better to
implement Runnable.
Thread
safety: When we implement Runnable interface, same object is
shared amongst multiple threads, but when we extend Thread class each and every
thread gets associated with new object.
Coding
to interface: Prefer to implement Runnable over
extending Thread. Thread class implements Runnable interface.
Inheritance
(Implementing Runnable is lightweight operation):
When we extend Thread unnecessary all Thread class features are inherited, but
when we implement Runnable interface no extra feature are inherited, as
Runnable only consists only of one abstract method i.e. run() method. So,
implementing Runnable is lightweight operation.
Don’t
extend Thread class unless you want to modify fundamental behavior of class,
Runnable interface has only one abstract method i.e. run().
No comments:
Post a Comment