Tuesday, 6 October 2015

Implement thread using Runnable interface or extend Thread class

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().

ExecutorService: If we implement Runnable, we can start multiple thread created on runnable object  with ExecutorService (because we can start Runnable object with new threads), but not in the case when we extend Thread (because thread can be started only once).

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...