What will be the result of an attempt to compile and run the following program? (Choose 1 Answer) } a. Result cannot be predicted 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 :
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. 

 
 
No comments:
Post a Comment