Implement Runnable or Thread Extension?

Asked

Viewed 3,368 times

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 the right way?
  • Is there any advantage or limitation?

1 answer

4


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 type of Thread, while it is just a Task thread.

By extending Thread your class will receive methods (by inheritance) that probably don’t make sense to it. This may even violate the "Principle of Liskov’s Substitution" and bring 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 type of Thread, and this makes sense in your Application. Otherwise, implement Runnable, because, if you extend Thread you will not be able to extend anything further, but if you implement Runnable you will still be able to extend another Class.

Also, if you look at the Classes "Threadpoolexecutor", "Executorservice", etc. (which allow you to improve performance with multiple Threads while controlling the amount of Threads so your computer won’t lock) you’ll see that they receive Tasks, ie, receive Runnable Objects instead of Threads; this way, if you implement Runnable your code can be used as a Task of a "Thread Pool" that manages the Threads for you.

  • A controversial point in implementing runnable is that you need to follow the signature of the run method and cannot release checked exceptions, for example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.