| Author |
Setting target at Thread's constructor
|
Avin Sharma
Greenhorn
Joined: Jan 17, 2013
Posts: 5
|
|
Regards,
I am new to Java. I am confused about Threads,When i am implementing thread with Runnable interface why i have to put "this" in Thread constructor.Please Explain in good Manner.Thank you
class NewThread implements Runnable
{
Thread t;
NewThread( )
{
t=new Thread(this, "Demo Thread"); //why i have to put this here
System.out.println("Child Thread:"+t);
t.start( );
} -----------*
|
 |
Devaka Cooray
Saloon Keeper
Joined: Jul 29, 2008
Posts: 2691
|
|
You do not have to pass 'this', unless you want to have the run() implementation of the current object invoked when the thread starts. As specified in the documentation,
http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#Thread(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String)
If the target argument is not null, the run method of the target is called when this thread is started. If the target argument is null, this thread's run method is called when this thread is started.
By passing 'this' to the constructor, you are setting the current object of NewThread to be the target in which the run() method should be invoked.
Please consider to UseAMeaningfulSubjectLine instead of something like "Java".
|
Author of ExamLab (Download) - the free mock exam kit for SCJP / OCPJP
Home Page -- Twitter Profile -- JavaRanch FAQ -- How to Ask a Question
|
 |
Avin Sharma
Greenhorn
Joined: Jan 17, 2013
Posts: 5
|
|
|
Thank you Devaka,But Please can you elaborate your answer. I didn't get your answer though,Sorry if it seems to be Silly But i am very new to Java-Threads. I don't get stuff easily.
|
 |
Steve Luke
Bartender
Joined: Jan 28, 2003
Posts: 3032
|
|
This recent discussion may help.
In your code, there is nothing special about the this keyword. You are passing an instance of a Runnable to the constructor. The class running the code happens to implement the Runnable, so it can use the this keyword to pass itself to the Thread.
|
Steve
|
 |
Avin Sharma
Greenhorn
Joined: Jan 17, 2013
Posts: 5
|
|
|
Thanks Everybody and Thanks Steve,i guess this conversation make me Clear.
|
 |
 |
|
|
subject: Setting target at Thread's constructor
|
|
|