Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

could you pls explain this code and the output.

 
Supriya Nimakuri
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will happen when you attempt to compile and run the following code?

How will a b.run(); a valid condition. instead of b.start();

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
 
Peter MacMillan
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As written, that code will compile and run cleanly without any output (4).

To understand why, examine the java API for the Thread.start and Thread.run methods.

As a hint, here is a modified version that will produce output:




hint: the default run method is essentially empty (well, it will try to use a delegate Runnable, but that's not applicable in this case). The code from your question overrides the start() method and calls the Thread.run() method.

Hope that helps.
[ June 27, 2006: Message edited by: Peter MacMillan ]
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

How will a b.run(); a valid condition. instead of b.start();


Can the run() Method Be Called Directly to Start a Thread?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic