Search This Blog

Friday, January 28, 2011

Question 2

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){
    	new Thread(new ThreadHelper(),"A").start();
    	new Thread(new ThreadHelper(),"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).
Thread Prediction is creating two separate objects of ThreadHelper. So the synchronized(str) of one object does not stop the execution of the other object. 

Question 2SocialTwist Tell-a-Friend

No comments:

Post a Comment