Should you extend Thread or implement Runnable in Java?
Implement Runnable in most cases. It separates the task from the thread, leaves your class free to extend something else, and works with thread pools. Extending Thread only makes sense if you are changing the thread behaviour itself.
Explain it simply
A Runnable is a job card, and a Thread is a worker. You can give the same job card to any worker, or to a pool of workers. Extending Thread glues the job and the worker together so you can never reuse either on its own.
Example
class PrintJob implements Runnable {
public void run() {
System.out.println("job on " + Thread.currentThread().getName());
}
}
Thread t = new Thread(new PrintJob(), "worker-1");
t.start(); // prints: job on worker-1
Runnable lambda = () -> System.out.println("lambda job");
new Thread(lambda).start(); // Runnable is a functional interfaceWhat to say in the interview
"Java has single inheritance, so extending Thread uses up my only superclass. Runnable lets the class extend another one, lets many threads share one task object, and can be passed to an ExecutorService. It is also a functional interface, so I can write it as a lambda. The cost of each is the same: a Thread is created only when I call new Thread or a pool does it for me."
Common mistakes
- Creating a new Thread for every tiny task rather than using a pool.
- Calling run() directly, which does not start a new thread.