Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Implementing Runnable or Extending Thread class

 
ujjwal soni
Ranch Hand
Posts: 403
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I want to know which is the best way to create a thread in java

1) extending Thread Class

OR
2) implementing Runnable Interface

???

As both work in a similar manner, i want to know which 1 is best ?

Cheers,

Ujjwal B Soni
<baroda, Gujarat, India>
<919998971048>
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Implement Runnable. You should only extend thread if you are adding more functionality to it, or attempting to change the way it behaves. Most of the time you are just trying to get code to run in a thread, not change how the Thread works. That is what the Runnable is for.

Theory aside, the Runnable also gives you more flexibility at lower cost. You can use Runnables with Executors in the java.util.concurrent package, and in Thread pools available from many sources. And you don't get any of the overhead that a Thread has when implementing it.
 
ujjwal soni
Ranch Hand
Posts: 403
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic