File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Threads: start() and run() methods 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 "Threads: start() and run() methods" Watch "Threads: start() and run() methods" New topic
Author

Threads: start() and run() methods

Swapna James
Ranch Hand

Joined: Jul 26, 2005
Posts: 56
Hi,

This is a question from Marcus Green's mock exam.

What will happen when you attempt to compile and run the following code?

public class Bground extends Thread{
public static void main(String argv[]){
Bground b = new Bground();
b.run();
}
public void start(){
for (int i = 0; i <10; i++){
System.out.println("Value of i = " + i);
}
}
}

1) A compile time error indicating that no run method is defined for the Thread class
2) A run time error indicating that no run method is defined for the Thread class
3) Clean compile and at run time the values 0 to 9 are printed out
4) Clean compile but no output at runtime

Ans: 4) Clean compile but no output at runtime

Can anybody tell me what happens when b.run() is executed?

Regards,
Swapna


SCJP 1.4
Adam Czysciak
Ranch Hand

Joined: Feb 25, 2005
Posts: 90
    
    5
Can anybody tell me what happens when b.run() is executed?


run() is the method from Runnable interface, which Thread implement. If you want to start new thread, you have to call start() method which calls run() then. In this example, run() is called directly so it doesn't in fact run in a seperate thread, but in current one. The run() method of inherited Thread class is called (as it's not overridden), which does nothing.


Adam
SCJA, SCJP 5.0, SCWCD 1.4, SCBCD 5, SCEA 5
Nibin Jacob Panicker
Greenhorn

Joined: Aug 16, 2005
Posts: 22
When b.run() is executed,it will call the run() in the parent class ie the Thread class.The Thread class has blank implementation of run() method like

public void run(){
}

so calling b.run() wont give any output..
Swapna James
Ranch Hand

Joined: Jul 26, 2005
Posts: 56
Thanks Guys......
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Threads: start() and run() methods