Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Setting target at Thread's constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Setting target at Thread Watch "Setting target at Thread New topic
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
ExamLab Creator
Saloon Keeper

Joined: Jul 29, 2008
Posts: 3100
    
  40

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 ExamLab - a free SCJP / OCPJP exam simulator
What would SCJP exam questions look like? -- Home -- Twitter -- 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: 4181
    
  21

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Setting target at Thread's constructor