Search This Blog

Friday, January 28, 2011

Question 11

What would be the result of an attempt to compile and run the following code?
Choose one answer.

public class OrderedThread {
  public static void main(String[] args) {
    ThreadHelper first,second,third;
    OrderedThread ot = new OrderedThread();
    first = new ThreadHelper("one",ot);
    second = new ThreadHelper("second",ot);
    third = new ThreadHelper("third",ot);
    second.start();
    first.start();
    third.start();
  }
  public void display(String msg){
    synchronized(msg){
      for(int i=0;i<20;i++){
        System.out.println("Name= "+msg);
      }
    }
  }
}
class ThreadHelper extends Thread{
  String name;
  OrderedThread ot;
  ThreadHelper(String name, OrderedThread ot){
    this.name = name;
    this.ot = ot;
  }
  public void run(){
    ot.display(name);
  }
}
Options :

A .The code compiles fine and prints Two, One, and Three in order and repeats the same for another 19times.
B. The code compiles fine and prints Two 20 times, One 20 times, and Three 20 times sequentially. However, the order whether Two will come first, then One, and at last Three is not guaranteed.
C. The code compiles fine and prints Two 20 times, One 20 times, and Three 20 times sequentially at the behavior is guaranteed.
D. The code compiles fine and prints Two, One, and Three 20 times each in an indefinite order.
E. The code compiles fine but throws InterruptedException due to synchronization of msg String in a  wrong way.



Answer : D


This is slightly tricky. The msg variable present in the display method is a local variable, so for every thread it creates a new local variable msg. So synchronizing the msg variable does not block the other threads to execute the display method. So D is correct and all other options are incorrect.


PS : If the msg would have been a instance variable then the answer will be C. Because there will be only a single msg variable and the first thread who acquires lock on the instance variable will block the other threads to execute the method.

Question 11SocialTwist Tell-a-Friend

No comments:

Post a Comment