Forums Register Login

Threads: start() and run() methods

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
 

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.
+Pie Number of slices to send: Send
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..
+Pie Number of slices to send: Send
Thanks Guys......
F is for finger. Can you stick your finger in your nose? Doesn't that feel nice? Now try this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 724 times.
Similar Threads
class extends thread-- shud u define run method?
Marcus Green Mock # 2 Ques. 18, 33, 51
Thread
could you pls explain this code and the output.
Thread2
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 04:28:02.