Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

override Thread.start()

 
Simon Cockayne
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,



1) Gives output:

main:Thread[main,5,main]
run:Thread[x,5,main]

Which is as one should expect.

x.start() starts the thread which runs the code in the run() method.

2) But...rename startZ to start, i.e. overriding Thread.start() gives output:

main:Thread[main,5,main]
Start:Thread[main,5,main]
run:Thread[main,5,main]

I.e. A new thread is NOT started.

So, questions:

Why would one want to override Thread.start()?

Why isn't it marked final?

Cheers,

Si.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, whenever you override something, you're expected to do it in a way that does not violate the stated API of the original method. The API says start() is supposed to start a thread; therefore you shouldn't override it in a way that does not start a new thread. But Sun can't prevent every possible coding mistake you might make. The decided to give us the power to revise behavior of methods in our classes; it's our responsibility to use this power sensibly.

Here's one possible example of an override of start() that does something potentially useful, but still fulfills the requirements of the API:

The key is that at some point, amidst doing whatever other functionality you want to add, you call the original method you're overriding. Depending on what class and method you're dealing with, in some cases you may not need to call the original method while overriding; in other cases, it's your only sensible option.
 
Simon Cockayne
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jim,

Thanks for the swift reply.

What you say sure makes sense...

I was limiting my thinking to doing initialising and so forth in the thread's constructor.

However, I am now the wiser (note - not the wisest).

Cheers,

Si.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic