I know there are two ways to use a thread in java:
I also know implementing Runable is better than extending Thread.
But why there are two ways - why not only one?
If implementing Runnable is a better approach, why is there another option?
What would be wrong with having only one option ?
Java threads can be created graciously in two ways: implementing the Runnable interface and extending Thread class. Extending the class inherits the methods and data members, fields from the class Tread. In this process only one class can be inherited from the parent class Thread.
First of all, each thread will consume CPU time to work. Therefore, if our application is running on a computer with a single-core CPU, it's impossible to start two threads at exact same time.
In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run concurrently on a separate processor, resulting in parallel execution, which is true simultaneous execution.
extends Thread
:
your thread creates unique object and associate with it
implements Runnable
:
it shares the same object to multiple threads
Another thing to note, since you can extend only one class in Java, if you extends Thread
, you can't extend another class. If you choose to implement Runnable
, you can extend class then.
By extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same runnable instance.
Just another reason why we use each type of threading.
Extending Thread
class will not give you an option to extend any other class. But if you implement Runnable
interface you could extend other classes in your class..
So depending on your design requirement you could use either of the menthods.
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