Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on Threads

 
Ravi Anamalay
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
1. class MyThread extends Thread {
2.public static void main(String args[]) {
3.MyThread t = new MyThread();
4.Thread x = new Thread(t);
5.t.start();
6.}
7. }

Now this was taken from Kathy & Bert's book - and the code works. I don't understand line 4 though. I thought that Thread constructor only took combinations of Runnable, String, ThreadGroup or nothing.
How come this works with an instance of MyThread, a subclass of Thread ?
Thanks in advance.
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ravi,
Line 4 works because Thread implements Runnable interface, so subclass of Thread (myThread) can be cast to Runnable.
HTH
 
Ramnath krishnamurthi
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ravi,
since MyThread is a subclass of Thread
t.start() will work.But am also surprised at the line
Thread x = new Thread(x).
Looking for an answer.
Thanks,
Ramnath
 
Ramnath krishnamurthi
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Lin.
 
Ravi Anamalay
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Chi,
So an implicit cast from Thread to Runnable has taken place ? How do we know when such an implicit cast takes place ? Thanks.
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ravi,
As I understand implicit cast is performed by compiler if the cast is a widening conversion/upcast along the inheritance hierarchy.
eg : child class cast to parent class or interface implemented by the parent class

Originally posted by Ravi Varman:
Hi Chi,
So an implicit cast from Thread to Runnable has taken place ? How do we know when such an implicit cast takes place ? Thanks.
 
Ravi Anamalay
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chi,
Thanks - much appreciated.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic