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{String str = new String("Running");public void run(){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 : C (Prints AABB or BBAA).
Thread prediction creates a single object ThreadHelper and shared it between both the threads. Both the Threads use the same instance variable str. If Thread A enters the synchronized block first then it will block the Thread B until completion of the synchronized block. Same is the case if Thread B enters first.
No comments:
Post a Comment