Tuesday, 27 March 2018

Difference between Thread and Runnable interface in Java.


A. 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.

B.When you extends Thread class, each of your thread creates unique object and associate with it.
When you implements Runnable, it shares the same object to multiple threads.

C.Use Runnable interface when you want to access the same resource from the group of threads. Avoid using Thread class here, because multiple objects creation consumes more memory and it becomes a big performance overhead.

D.Loosely-coupled : "implements Runnable" makes the code loosely-coupled and easier to read .
Because the code is split into two classes . Thread class for the thread specific code and your Runnable implementation class for your job that should be run by a thread code.
"extends Thread"  makes the code tightly coupled . Single class contains the thread code as well as the job that needs to be done by the thread.

No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...