Implement Runnable or Extend Thread?

3

In several Java projects, I've 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 way?
  • Is there any advantage or limitation?
asked by anonymous 04.04.2017 / 16:50

1 answer

4

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

When you extend Thread your class will receive methods (by inheritance) that probably do not make sense to it. This may even violate the "Principle of the Substitution of Liskov "

Finally, extend Thread only if you need a new Thread type, and this makes sense in your Application. Otherwise, implement Runnable, because, if you extend Thread you will not be able to extend anything else, but if you implement Runnable you can still extend another Class.

In addition, if you look at the "ThreadPoolExecutor" classes < a>, "ExecutorService" , etc. (which allow you to improve performance with multiple Threads while controlling the amount of Threads your computer will not load) you will see that they receive Tasks , that is, they get Runnable Objects instead of Threads ; so if you implement Runnable your code can be used as a Task of a Thread Pool that manages Threads for you.

    
05.04.2017 / 21:53