This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt in thread constructor.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt in thread constructor.." Watch "doubt in thread constructor.." New topic
Author

doubt in thread constructor..

Ganeshkumar cheekati
Ranch Hand

Joined: Oct 13, 2008
Posts: 362
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?


SCJP5 and SCWCD1.5
Think Twice Act Wise...
Paul Somnath
Ranch Hand

Joined: May 19, 2008
Posts: 177
This is because the java.lang.Thread implements the Runnable interface.
Read the java docs.


Preparing for SCJP 6.0
Bob Ruth
Ranch Hand

Joined: Jun 04, 2007
Posts: 320
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.


------------------------
Bob
SCJP - 86% - June 11, 2009
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: doubt in thread constructor..
 
Similar Threads
Query on threads ?
Query on Threads
Declaring an Anonymous Class...
Interrupting a Thread
synchronization confusion