Win a copy of Real-World Software Development: A Project-Driven Guide to Fundamentals in Java this week in the Agile and Other Processes forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Liutauras Vilda
  • Knute Snortum
  • Bear Bibeault
Sheriffs:
  • Devaka Cooray
  • Jeanne Boyarsky
  • Junilu Lacar
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • salvin francis
Bartenders:
  • Tim Holloway
  • Piet Souris
  • Frits Walraven

starting a thread in a constructor

 
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it a normal idiom to start a thread in the constructor of the Runnable object?
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's a bit unusual, but I've seen it a few times. Bruce Eckel does it in all his Thread classes. My feeling is that if your classes will be used by any other developers, you should probably avoid unexpected behavior like this. Or alternately, make sure it's well-documented.
Essentially, if I see a class that extends Thread, I assume that I should call start() to start it. If I see a class that implements Runnable without extending Thread, I assume it's my job to create a Thread object to start it. Those are the standard idioms as far as I'm concerned, and if a class doesn't follow them I'd expect to be warned about it.
Note that for class A one option is to hide the Runnable aspect entirely by using a nested or inner class. E.g.

This may be a little more complex on the inside, but it has the advantage that someone looking at a javadoc-generated API for this class won't think "hey, it's a Runnable, therefore I should create a Thread for it."
[ July 08, 2003: Message edited by: Jim Yingst ]
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Jim for your ideas.
Also, since your hidden Runnable is private, no one is going to invoke the run method except the Thread. Good idea.
Here is a variation on your hidden Runnable, essentially the same thing.
 
Evildoers! Eat my justice! And this tiny ad's justice too!
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!