Java Programming - Threads - Discussion
Discussion Forum : Threads - Finding the output (Q.No. 14)
14.
What will be the output of the program?
class Test116
{
static final StringBuffer sb1 = new StringBuffer();
static final StringBuffer sb2 = new StringBuffer();
public static void main(String args[])
{
new Thread()
{
public void run()
{
synchronized(sb1)
{
sb1.append("A");
sb2.append("B");
}
}
}.start();
new Thread()
{
public void run()
{
synchronized(sb1)
{
sb1.append("C");
sb2.append("D");
}
}
}.start(); /* Line 28 */
System.out.println (sb1 + " " + sb2);
}
}
Answer: Option
Explanation:
Can you guarantee the order in which threads are going to run? No you can't. So how do you know what the output will be? The output cannot be determined.
add this code after line 28:
try { Thread.sleep(5000); } catch(InterruptedException e) { }
and you have some chance of predicting the outcome.
Discussion:
11 comments Page 2 of 2.
Rksh25 said:
6 years ago
sb1 lock obtain by thread 1 and prints A and B. Just after this if T2 starts will get AB CD. In between the execution of T1, if T2 also starts it won't get lock so no output from T2 run method. We are not using wait n notify here for communication between t1 and t2.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers