Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in thread constructor..

 
Ganeshkumar cheekati
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class MyThread3 extends Thread {
public static void main(String [] args) {
MyThread3 t = new MyThread3();
Thread x = new Thread(t);
x.start();
}
public void run() {
for(int i=0;i<3;++i) {
System.out.print(i + "..");
}
}
}

in the above code i am creating object for MyThread3 class and passing the reference variable to the constructor of Thread.

we have to pass only Runnable reference variable to the constructor of Thread because "Thread(Runnable target)"

how it is working?
 
Paul Somnath
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is because the java.lang.Thread implements the Runnable interface.
Read the java docs.
 
Bob Ruth
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thread, as it comes, implements Runnable and I believe has an empty run() method to satisfy the override required to implement Runnable. In the problem you show, MyThread3 has a run() method which overrides the run method that it's superclass Thread defined.

When it comes to the Thread creation to start a new thread, you instantiate a Thread you pass a reference to a Runnable. Since all threads implement Runnable, they pass the IS-A test, so you can pass a Thread to another thread. In this case, the run() that will be called when the thread starts is the override version defined in MyThread3().

This may sound a little confusing but read it a couple of times and let it sink in.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic