Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scenario of extending Thread class and implementing Runnable interface [duplicate]

I am new to thread programming in Java and hence this basic question. (I checked, but could not find this question previously asked)

I read that threads can be created either by inheriting the Thread class or by implementing the Runnable interface. I saw a code which had both to the same class.

public class ThreadExample extends Thread implements Runnable {
}

I was wondering what kind of situation would want this and if there is any advantage to this, what is it.

like image 709
noMAD Avatar asked Jan 21 '12 22:01

noMAD


People also ask

In which scenario Thread class or runnable interface is suitable?

A class that implements Runnable is not a thread and just a class. For a Runnable to become a Thread, You need to create an instance of Thread and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods.

Can we extend Thread and implement runnable at the same time?

You should almost never do that. The type Thread already implements Runnable . The only reason to do this is if you want to be explicit in your source code. There is only one way to create a thread: creating a Thread instance and invoking its start() method.

When should we create Thread by implementing runnable and extending Thread class?

A user must extend thread class only if it wants to override the other methods in Thread class. If you only want to specialize run method then implementing Runnable is a better option. Implementing Runnable interface introduces loose coupling as the code of Thread is separate form the job of Threads.

How Thread can be created by extending the Thread class explain with example?

In this example program, we create a class MyThread with run() method. The class MyThread extends Thread class so that we are overriding run() method of Thread class to perform a specific task. 2. We created an object of MyThread class with reference variable th so that run() is available for execution.


2 Answers

No, There is no advantage of using this approach, because, Thread class implements Runnable interface. So, if your class extends Thread class. It means, it's also implementing Runnable interface.

http://www.developerfusion.com/pix/articleimages/may05/javathread3.jpg

like image 120
mogli Avatar answered Nov 18 '22 14:11

mogli


extending Thread and implementing Runnable is useless (Thread already implements Runnable). You pretty much always want to implement Runnable (and not extend Thread). That gives you the flexibility of using a Thread directly (not recommended) or using one of the newer ThreadPool implementations in java.util.concurrent (recommended).

like image 42
jtahlborn Avatar answered Nov 18 '22 12:11

jtahlborn