Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why there are two way of using thread in java? [duplicate]

I know there are two ways to use a thread in java:

  1. implement Runable
  2. extend Thread

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 ?

like image 617
TKumar Avatar asked Jun 26 '13 04:06

TKumar


People also ask

Why there are 2 ways to create thread in Java?

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.

Can two threads execute at the same time Java?

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.

Can two threads execute at the 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.


3 Answers

  • 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.

like image 119
Maroun Avatar answered Oct 04 '22 15:10

Maroun


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.

like image 34
Rajan Garg Avatar answered Oct 04 '22 15:10

Rajan Garg


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.

like image 33
blganesh101 Avatar answered Oct 04 '22 16:10

blganesh101