This question may sound too naive, but the most stupid question is the one which is not asked. So here it is..I wonder why there is a no argument constructor in Thread class, and there is a run method which does nothing.
is it the only use? i.e. to create subclasses, without explicitly calling the Super-class constructor. or is there more to it ?
amit punekar
Ranch Hand
Joined: May 14, 2004
Posts: 488
posted
0
Hello,
You can write the code that should be executed as part of the thread in the run() method.
The example that you have pasted below will save you from writing a complete Java class to do the same thing.
I believe this kind of construct is like Annonymous class where you instantiate the an Annonymous class and provide implementation for abstract method.
The code that I have mentioned(as an anonymous class) is the very first thng that came to my mind, when I tried to find an answer.
My question still remains unanswered that, is this the only motive for non-argument constructor, in Thread class or there is something more to it?
why there is a no argument constructor in Thread class
Not sure how this is verified, but Thread class actually has a no arg constructor.
From the code of Thread class,
/**
* Allocates a new <code>Thread</code> object. This constructor has
* the same effect as <code>Thread(null, null,</code>
* gname<code>)</code>, where gname is
* a newly generated name. Automatically generated names are of the
* form <code>"Thread-"+</code>n, where n is an integer.
*
* @see #Thread(ThreadGroup, Runnable, String)
*/
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
And the run method()
public void run() {
if (target != null) {
target.run();
}
}
The job of run() method is just to execute the run() of the runnable object passed to it in a new thread of execution. So, if there is no target runnable, then this thread is not supposed to execute anything and hence it will not do anything.
Hope this is clear.
What I want to know is "the purpose" for having no-argument constructor in Thread class.
The code for run method and constructor is all fine.
I would like to know where one can "USE IT".
But that constructor could have been protected, and you could still use it for sub classing. I'm with Rohit here, I don't see any value in having that constructor in its current form.
Thread stems from the old Java 1.0 days. There are quite a lot more oddities in that old code, some even worse than this (like java.util.Stack extending java.util.Vector, which allows for random access of the Stack elements through the inherited methods). Even though Sun created the language, its designers were just as perfect in their designs as anyone else - not perfect at all. My guess is that if Thread would have been created these days, this constructor would have been protected.