I just learn the theory about thread. And there is Thread and Runnable.
class A extends Thread{
public void run(){
while(true) {
System.out.println("Hi");
}
}
}
class B implements Runnable{
public void run(){
System.out.println("Hi");
}
}
Thread is good with rich API, so why would I use Runnable instead of Thread?
Thanks.
When we extend Thread class, we can't extend any other class even we require and When we implement Runnable, we can save a space for our class to extend any other class in future or now. When we extend Thread class, each of our thread creates unique object and associate with it.
If you want to implements or extends any other class then Runnable interface is most preferable, otherwise, if you do not want any other class to extend or implement then Thread class is preferable.
The runnable interface provides a standard set of rules for the instances of classes which wish to execute code when they are active. The most common use case of the Runnable interface is when we want only to override the run method.
1. Java doesn't support multiple inheritance, which means you can only extend one Java class, so once you extended Thread
class you lost your chance and cannot extend(inherit) another class in java.
2. In OOP extending a class generally means adding new functionality, modifying or improve behaviors. If you are not making any modification on Thread
, then use Runnable
interface instead.
3. Implementing Runnable
makes your class more flexible(you can implement more than one interface).
One of the big advantages is: you don't have to run a Runnable
on a new thread.
One day, you might decide that instead of running it on a new thread, you should run it directly (on the current thread), or on a thread pool - and then you can change new Thread(runnable).start()
to threadPool.submit(runnable)
or runnable.run()
- and the change only affects one place.
Also, if you leave a Runnable
hanging around, it doesn't waste resources - it doesn't count towards the thread limit (if there is one), and it doesn't reserve space for a stack. Say you wanted to have a queue of things to do one at a time - sure, you could have a Queue<Thread>
and then start each thread when the previous one finished, but then you're wasting a lot of memory with non-running threads. If you used a queue of Runnable
s, you don't use as much memory except when they're actually running.
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