This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why Thread.start()?

 
Arun Maalik
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear ranchar i having a code for a thread as below


Well the above code will work fine as i have expected but tell me why we are calling the start method by Thread object we can call the start method as below

First p=new First();
p.start();

and will pwork fine then what is the need of Thread object there.

Regard
Arun
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right, it's not needed.

Or better yet, it's not necessary that First extends Thread. Let it implement Runnable instead, and all still is fine. (Your code works because Thread implements Runnable, too.)
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Compromise:

Thread first = new First();
first.start();

Bu. ;)
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We have a number of reasons to prefer implementing Runnable over extending Thread.

When you extend any concrete class you expose yourself to risk in the event the superclass changes one day. This article explains why in perhaps overly dramatic language.

When you extend Thread you tell the world that your task "is a" thread, which isn't true (unless you want to modify the way Threads work.) It's some code that can be run on a thread.

When you implement Runnable you can also extend something else. If you extend Thread you're stuck with Thread.

None of those are drop dead reasons to never extend Thread, but they add up to a strong preference to get in the habit of implementing Runnable.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic