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.
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.
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With