Use of creating a Thread by extending a Thread class

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

Java provides two options to create a Thread class ie 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


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.


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

eg

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 ie 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 .

链接地址: http://www.djcxy.com/p/92076.html

上一篇: 线程创建和启动

下一篇: 通过扩展一个Thread类来创建一个Thread