• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads: start() and run() methods

 
Swapna James
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Adam Czysciak
Ranch Hand
Posts: 90
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Nibin Jacob Panicker
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Guys......
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic