why there are two way of using thread in java?

18,576

Solution 1

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

Solution 2

Technically, there is only one way: implement Runnable. Thread, incidentally, does just that, so extending it you trivially satisfy the interface requirement.

Solution 3

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.

Solution 4

Even if you implement Runnable interface you will need to create thread to let your task run as a thread. obvious advantages you get out implementing Runnable are

  1. You have liberty to extend any other class
  2. You can implement more interfaces
  3. You can use you Runnable implementation in thread pools

Extending Thread class is just an option as it implements Runnable internally so you end up implementing Runnable interface indirectly. Its just that this class was not made final to prevent developers from extending it. As Joshua Bloch mentions in 'Effective Java' that there should be no reason to extend Thread usually

Solution 5

Using Thread as a task provides a compact way to create and run a parallel thread

new Thread() {
    public void run() {
        ...
    }
}.start();
Share:
18,576
TKumar
Author by

TKumar

I am working as an android developer.

Updated on June 03, 2022

Comments

  • TKumar
    TKumar about 2 years

    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 ?