7

Possible Duplicate:
Java: “implements Runnable” vs. “extends Thread”

Java provides two options to create a Thread class i.e either by implementing Runnable or by extending Thread class.

I know there can be many reasons to implement a Runnable but not sure where the scenario would be to extend a Thread class to create own Thread class?

Could you please provide me scenarios where extending Thread seems to be feasible or better option or advantageous...

There was a Question on the threads but that did'nt answer my question

Community
  • 1
  • 1
Satya
  • 2,094
  • 6
  • 37
  • 60

2 Answers2

2

There is almost no reason to extend Thread, basically the only reason you would want to extend thread is if you were going to override things other than run() which is generally a bad idea. The reason it is less common to extend Thread is because then the class can't extend anything else, and if you're only overriding the run() method, then it would be kinda pointless to extend Thread and not implement Runnable.

John
  • 3,769
  • 6
  • 30
  • 49
0

Runnable is an interface with just one method run() that needs to be implemented by the class implementing the interface.

e.g.

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        //...
    }
}

MyRunnable is not a Thread nor can you create a new thread just by using that class. So, it doesn't quite make sense to say -

Java provides two options to create a Thread class i.e either by implementing Runnable ...

You can extend the Thread class but just like @John said there isn't any point in doing so.

But if you want to execute some code in a new thread then the following is the best way -

MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();

t.start() method starts a new thread and invokes run() method on r (which is an instance of MyRunnable.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
  • I actually know this concept of how to create a Thread, but wanted to know where I actually create a Thread by extending a class rather than implementing an Interface ;) – Satya Jun 18 '12 at 05:42