• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread  RSS feed

 
lahiru nanayakkara
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why we cant assign thread object address to reference variable?explain
 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
lahiru nanayakkara wrote:why we cant assign thread object address to reference variable?explain


Not sure what you mean by object address as we don't really deal with addresses in Java. And what reference variable? Reference variables have a type.
You know that the following is legal..



And following is not allowed.


A Thread is just any other object. And Java allows you to assign a sub class reference/object to a super class reference without casts. Nothing to do specifically with threads there. Is that what you were asking?
 
lahiru nanayakkara
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No,I mean we cannot assign thread object to "t1" variable.why is that?

Thread t1=new Thread();
 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
lahiru nanayakkara wrote: No,I mean we cannot assign thread object to "t1" variable.why is that?

Thread t1=new Thread();

I'm not sure if I understand you properly because the code you have shown is legal Java. It is constructing a new Thread object and assigning it to the variable t1.
 
Chan Ag
Rancher
Posts: 1090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
lahiru nanayakkara wrote: No,I mean we cannot assign thread object to "t1" variable.why is that?

Thread t1=new Thread();


Ok, I'm guessing you mean why we 'shouldn't' ( more on the lines of why it is pointless ) do the declarations such as the one you have mentioned. This is because the default run method in the Thread class does nothing. Of course you created the thread so it does something for you.

But if a Thread is created by passing a Runnable ( a Thread is a Runnable, and a Thread subclass - although it is a bad design at least in this context - is also a Runnable ) to its constructor, and this Runnable overrides the
method thereby specifying what instructions the Thread should execute once it is started, it makes sense to create a Thread.

Consider going through this page.

Edit : And just to emphasize what Tony said - it IS perfectly legal to create a Thread like this.



Just it does nothing after you start it. It finishes immediately.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't? This compiles fine for me:


Edit: Oops, posted before seeing Tony's and Chan's replies.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!