Search This Blog

Friday, January 28, 2011

Question 12

What would be the result of an attempt to compile and run the following code?

class TwoThreadsDemo extends Thread {
  public TwoThreadsDemo(String str){
    super(str);
  }
  public void run(){
    for(int i=0; i<10; i++){
      System.out.println(i+" "+getName());
      try{
        sleep((long)(Math.random()*1000));
      }catch(InterruptedException ie){
        ie.printStackTrace();
      }
      System.out.println("Done with Sleep !! "+getName());
    }
  }
}
public class SimpleThread{
  public static void main(String[] args){
    new TwoThreadsDemo("TwoThreadsDemo").start();
    new TwoThreadsDemo("TwoThreadsDemo").start();
  }
}
Options :


A: It will not compile because TwoThreadsDemo is a subclass of thread, but does not have a no-argument public constructor.
B. It will not compile because two separate threads in line A and line B have been given the same name "Java Programmer".
C. It will compile, but at runtime the second thread will overwrite the first thread and so the run method of the TwoThreadsDemo class will be executed only once instead of twice.
D. It will compile but will throw RuntimeException.
E It will compile and run with success and the run method of TwoThreadDemo class will be executed twice by two separate threads created.



Answer E :

This questions tests your understanding of thread constructor and thread naming. Always remember the following statement

Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.”

Option A is incorrect because a class will compile with out a no-argument public constructor. Option B & C are incorrect based on the above bold statement.Option D is incorrect because it does not throw a RuntimeException.

Question 12SocialTwist Tell-a-Friend

No comments:

Post a Comment