Search This Blog

Friday, January 28, 2011

Question 3

What will be the result of an attempt to compile and run the following program? (Choose 1 Answer)

public class ThreadPrediction {
    public ThreadPrediction() {
    }
    public static void main(String[] args){
      ThreadHelper th = new ThreadHelper();
      new Thread(th,"A").start();
      new Thread(th,"B").start();
    }
}
class ThreadHelper implements Runnable{  
  public void run(){
    String str = new String("Running");
    synchronized(str){
      try{
        System.out.println(Thread.currentThread().getName());
        Thread.sleep(5000);
        System.out.println(Thread.currentThread().getName());
      }catch(InterruptedException ie){
        ie.printStackTrace();
      }
    }
  }

}
Options :

a. Result cannot be predicted
b. Prints "ABAB" or "BABA"
c. Prints "AABB" or "BBAA"
d. Compiler Error
e. An exception is thrown


Answer : A (Result cannot be predicted)
This is slightly tricky question. The main method is using a single object th (ThreadHelper) and passing that same object to both the threads. Here is where you will be mislead. String str is a local object, so both threads create two copies of str so the lock on the first thread does not stop the other from executing.

Question 3SocialTwist Tell-a-Friend

No comments:

Post a Comment