Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why we need to override run

 
abhay jain
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why we need to override run ( ) to create a thread ?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because that's how they work! To create a thread you do one of two things:

- Write a class that extends Thread
- Write a class that implements Runnable, and pass an instance of that to a Thread object (via its constructor)

In the second case, you have to implement run() because it's part of the Runnable interface. In the first case, you don't have to override run(), but your thread won't do anything - without it you'd just get a new thread that exits immediately.

This is what is happening: when a thread is started it executes the run() method of the Thread object. The default implementation of this runs the run() method of any Runnable you've passed in. So that's where you have to put whatever code you want performing.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic