1

I know the basics of multithreading. Moreover, I referred this answer by Mr. Jon Skeet "implements Runnable" vs. "extends Thread".

Here he said:

You're not really specialising the thread's behaviour. You're just giving it something to run. (So use Runnable instead of Thread)

So my question is:

In what scenario one would specialise a thread?

When should you extend Thread in Java?

I would appreciate an answer with examples and codes.

Thanks!!

Community
  • 1
  • 1
John Rambo
  • 906
  • 1
  • 17
  • 37

3 Answers3

2

Think about the Runnable as a task to execute and about the Thread as an executor. You should extend Thread if you want to add some specific behavior to executor, like, maybe, controlling its lifecycle, modifying state, etc. An example of classes derived from Thread you can find in JDK(take a look here), Android SDK (take a look here).

nikis
  • 11,166
  • 2
  • 35
  • 45
0

One possible scenario is
When your class is childclass i.e. having superclass in that case you cant extend Thread , you have to implement Runnable interface And if class is not a childclass you can extend the Thread class.

swapnil7
  • 808
  • 1
  • 9
  • 22
-1

One thing which I could think of: If you want to have multiple threads, which by default would have e.g. a specific name or priority, you could extend Thread.

public class MyThread extends Thread {

    public MyThread() {
        super("MyThread");
        setPriority(Thread.MIN_PRIORITY);
    }

    @Override
    public void run() {
        // something
    }
}

Or if you want to make more operations related to the Thread object itself. Usually you don't need to do anything else than implement Runnable and create the Thread with the constructor that takes it as a parameter.

Bubletan
  • 3,833
  • 6
  • 25
  • 33
  • I didn't downvote it but instead of creating a subclass your chould just create a factory method if you want other default values. – Jimmy T. Apr 25 '15 at 17:15
  • @JimmyT. Yah, or just use some `Executor`. Was just one thing that could be done. – Bubletan Apr 25 '15 at 18:03