Implement Runnable or extend Thread?

In several Java projects, I have seen these two ways to create Threads:

With implements Runnable:

public class MyRunnable implements Runnable {
    public void run() {
        //Código
    }
}
//Iniciada com uma chamada "new Thread(new MyRunnable()).start()"

Or, with extends Thread:

public class MyThread extends Thread {
    public MyThread() {
        super("MyThread");
    }
    public void run() {
        //Código
    }
}
//Iniciada com uma chamada "new MyThread().start()"
  • What is the correct mode?
  • is there any advantage or limitation?
Author: Murillo Goulart, 2017-04-04

1 answers

According to the book " Use Your Head! Java " you should implement Runnable, because when you extend Thread you are saying that your class is a new Thread type, while it is just a Task of a Thread.

When extending Thread your class will receive methods (by inheritance) that probably don't make sense to it. This may even violate the "Liskov Substitution Principle" and cause you problems since your class may not be used in all situations where a Thread is used.

Anyway, extend Thread only if you need a new Thread type, and this makes sense in your application. Otherwise, implement Runnable, not least because, if you extend Thread you cannot extend anything else, being limited, but if you implement Runnable you can still extend another class.

Also, if you look at the Classes "ThreadPoolExecutor", "ExecutorService" , etc. (which allow you to improve you will see that they receive tasks , that is, they receive Runnable objects instead of Threads; in this way, if you implement Runnable your code can be used as a task of a "Thread Pool" that manages the Threads for you.

 4
Author: Douglas, 2017-04-05 20:12:40