Java Multithreading – Main Advantage of Extending Thread Class

javamultithreading

I'm trying to find out what are the possible advantages of extending the Thread class would be?

This is a part of another question which I describe:
There is two way of creating threads in Java

  1. extending from Thread class
  2. implementing the runnable interface

As expalined here there are several benefits of using runnable interface. My question is what is the advantage of extending from Thread class? The only advantage that comes to my mind is that one can extend from Thread class, and let's say call it ThreadExtended class. Then he/she can add more functionality in ThreadExtended(which I don't know what that might be), and then when he/she wants to create a thread, instead of extending from Thread class, it extends from ThreadExtended.

Is there any advantages in using Thread class instead of Runnable interface? Do you know any class(es) that extends from Thread class and then ask users to extends from those classes if they want to have multithreading capabilities?

    public class ThreadExtended extends Thread{
    //override some functions || add more functionality to Thread class
    }

    public class MyThread extends ThreadExtended{
     public void run()
    {
     for(int i=0;i<10;i++)
        {
          System.out.println("Using ThreadExtended instead of Thread directly");
        }
    }

    public static void main(String args[])
    {
    MyThread myThread = new MyThread();
    myThread.start();
    }
    }

Best Answer

There is rarely a compelling reason to extend the Thread class. I would imagine that in most cases, you would end up just throwing all of your 'do some stuff' logic into the run method anyway.

You should definitely stick with implementing Runnable. By choosing to extend Thread, you are creating a class hierarchy that probably is nonsensical and will wind up restricting your options for refactoring things in the future. By choosing to implement Runnable, you make no demands of what the lineage of the implementer is, and you can use powerful abstractions like the ExecutorService to abstract away the nuts and bolts of running a chunk of code. Finally, preferring to implement an interface rather than extend a class is a good practice!

Related Question