Search This Blog

Friday, January 28, 2011

Question 14

What will be the result of attempting to compile and run the following program?

public class CustomThread extends Thread{
  public void run(){
    callMethod();
  }
  public synchronized void callMethod(){
    System.out.println(Thread.currentThread().getName());
  }
  public CustomThread(String name){
    super(name);
  }
  public static void main(String[] args){
    CustomThread a = new CustomThread("A");
    CustomThread b = new CustomThread("B");
    b.start();
    b.yield();
    a.run();    
  }
}
Options :


a. Prints "BA"
b. Prints "AB"
c. Prints "Bmain"
d. Prints "mainB"
e. Output can be "Bmain" or "mainB"
f. Output can be "BA" or "AB"
g. Code does not compile



Answer :  E

Thread A is not at all started so the output cannot contain “A”. So options A,B,F are incorrect. run() method can be invoked directly , so there is no syntax error in the code so the option G is also incorrect. Now there are two threads running one is the main thread and other is Thread B. Yield method is executed on Thread B, this method causes pauses the current thread and allows other threads to execute. But this behavior is not guaranteed. So options C and D are incorrect.

Question 14SocialTwist Tell-a-Friend

No comments:

Post a Comment