• Post Reply Bookmark Topic Watch Topic
  • New Topic

Run Method vs. Extending Thread  RSS feed

 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the project I'm working on, I think it would be really nice to have a run method which would except parameters. Of course, I know that I wouldn't call the run method directly anyway, as I would use start().
So to compensate for the lack of parameter passing in the run method should I create another class that extends Thread and then create a new object with a constructor to pass the parameters?
Is this the appropriate way to handle this situation?
It seems like it's better than having global variables....
Thanks!
Drew
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's nothing wrong with subclassing Thread, as you suggest.
You can make use of some anonymous inner class magic, if you prefer. This allows you to implement Runnable, rather than subclassing Thread, while still providing arguments to the Runnable.
The advantage of implementing Runnable, rather than subclassing Thread, is that you can implement Runnable (and other interfaces, if you want) while subclassing something else of your choosing. This is because of the single inheritance of Java.
Example of anonymous inner class for Runnable:
<code>
/** Any method within any class of your choosing.
* @param param1 a value to be passed to the Runnable
*/
public void doSomething(final int param1)
{
// another value to be passed to the Runnable
final String param2 = getSomeData();
// Construct a Runnable using anonymous inner class
Runnable task = new Runnable()
{
public void run()
{
// do something with the values passed in
performOperation(param1, param2);
}
};
Thread taskThread = new Thread(task);
taskThread.start();
}
</code>
The values param1 and param2 are declared as final, and this is a requirement. Behind the scenes, the Java compiler creates a class file for the anonymous inner class here. That created class includes data and methods for access of the param1 and param2 values.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you don't like inner classes, you can avoid them by adding the parameters to the object that implements the task (let's call that TaskObject for now).When deciding between the above two solutions or extending Thread, ask yourself: do I need to run the task more than once? A Thread can just run once. On a more abstract level, is the task a Thread? or does it make use of a Thread? The former suggests extending Thread, the latter suggests not.
- Peter
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!