aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread" Watch "Thread" New topic
Author

Thread

jeena jose
Ranch Hand

Joined: May 06, 2001
Posts: 69
hi,
1)
please explain why these two codes behave differetnly.
this program will not print "Start"
that means evethough we are calling start method thread is directly going to run method

public class pmain implements Runnable{
public void start(){System.out.println("start");}
public void run(){
for(int i=0;i<2;++i){
System.out.println(i);
System.out.println(Thread.currentThread());
}}
public static void main(String args[])
{
pmain t=new pmain();
Thread t1=new Thread(t);
t1.start();
}
}

2)
this code print start but will not run "run method"
public class pmain extends Thread{
public void start(){System.out.println("start");}
public void run(){
for(int i=0;i<2;++i){
System.out.println(i);
System.out.println(Thread.currentThread());
}}
public static void main(String args[])
{
pmain t1=new pmain();
t1.start();
}
}
Nagarajan Subramanian
Greenhorn

Joined: Mar 18, 2001
Posts: 11
Hi jeena,
I will try to explain this one.
1) The start method is defined in the the Thread class and not in the Runnable interface. So when you define the start method, you are not implementing a method in the interface but it is your own new method. When t1.start() is executed, it will call the start method if Thread object t1 which in turn will call the run() method in Thread t1 which in turn will call the run() method in the Runnable object t.
This is from JDK docs:
-------
When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.
------
2) In this class you have extended the Thread class and are overriding the start method. The start method in the Thread class has been defined already to call the run() method in the same class but since you have overridden it, the functionality is lost. If the you remove the start method in this case, you will the run() method execute.
Fromt the JDK docs:
--------
Start method
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
----------

Anybody, please correct me if wrong.
Thanks
Zkr Ryz
Ranch Hand

Joined: Jan 04, 2001
Posts: 187
Im totally agree with you
nagarajan subramanian.
Jeena in your code you are calling the start method.
In the first example, you are callin the Thread start() method, not the pmain start() method.
In the second example you are calling the start() method of pmain, which is a subclass of Thread, but start() method is overriden and print "start".
So I agree with nagarajan.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread