Tuesday, 22 August 2017

multithreading - why there are two way of using thread in java?




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 ?


Answer




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


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...