Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Setting target at Thread's constructor

 
Avin Sharma
Greenhorn
Posts: 5
Android Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 4684
336
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
Avin Sharma
Greenhorn
Posts: 5
Android Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Avin Sharma
Greenhorn
Posts: 5
Android Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Everybody and Thanks Steve,i guess this conversation make me Clear.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic