• Post Reply Bookmark Topic Watch Topic
  • New Topic

what is the target of a thread

 
wei wu
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I will be very grateful if you can help me
I picked out the following code from class file:
java.lang.Thread

And now, I write a subclass of Thread named MyThread and I don't explicitly call super() in its constructor.
What if I write: new MyThread() Will it calls the default constructor of Thread? And its target will be set null? But I think its target should be set to this
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What if I write: new MyThread() Will it calls the default constructor of Thread?
Yes, unless you provide a constructor which explictly calls a different super() constructor.
And its target will be set null?
Yes.
But I think its target should be set to this
Well, you can write a constructor for MyThread which does this for you. Or you can override run() so that the target is not needed. I.e. Thread's run() looks like this:

If you use Thread's run() method, you need a target. However the other common way to use Thread is to override run() in a new class (like MyThread) - if you do this, you don't need the target; it can be null, as it's basically ignored.
 
wei wu
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jim
But I think Erery thread, without exception, should have a target. For the task of a thread is to run the run() method of its target.
I can imagine the native code of start() method:
Create a new thread using windows API
Set the target code of the thread
Run the thread
 
Wilson Mui
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am a real newbie at Threads, but it really sounds like the "target" that you guys are referring to is always just the same class that owns the run method. So are you saying that the target of a Thread, is just the Thread itself?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That seems to be what Wei is saying, but it's not consistent with what the API says. In the API, the "target" is an external Runnable object, passed to the Thread using the new Thread(Runnable) constructor (or a similar one). If there's no other Runnable, and the only run() method is the one for the Thread object itself (which is most likely a subclass of Thread rather than an actual Thread), then we say the target is null. It doesn't really matter much most of the time - but if you're looking at the Thread code and trying to understand what "target" means (as Wei was), the fact is that for a new Thread(), the target is null.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!