One of the most fundamental design question which is often asked in Java interviews is, if you were to create a new thread, would you extend Thread class or would you choose to implement Runnable and why.
Answer to this question is implement Runnable and the reason provided in most cases is that the class can extend any other class in future, if required. Though the answer is correct but, is that the good enough design consideration to create a new thread this way.
The actual design consideration is you should only extend Thread when you are "extending (enhancing)" the functionality provided by the Thread class and not for providing your business functionality. For instance, if you want to provide a Thread Class which can be Serialized(I don't know why and how you want to do that, this is just a hypothetical situation) and then this class can be used elsewhere as way to spawn serializable threads, then you should actually go ahead and extend thread but, if purpose to create a thread is to execute some business functionality, always go about implementing Runnable.
No comments:
Post a Comment