Tuesday, 15 November 2016

java - Scenario of extending Thread class and implementing Runnable interface




I am new to thread programming in Java and hence this basic question. (I checked, but could not find this question previously asked)



I read that threads can be created either by inheriting the Thread class or by implementing the Runnable interface.
I saw a code which had both to the same class.




public class ThreadExample extends Thread implements Runnable {
}


I was wondering what kind of situation would want this and if there is any advantage to this, what is it.


Answer



extending Thread and implementing Runnable is useless (Thread already implements Runnable). You pretty much always want to implement Runnable (and not extend Thread). That gives you the flexibility of using a Thread directly (not recommended) or using one of the newer ThreadPool implementations in java.util.concurrent (recommended).


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...