Sail E0 Webinar
Question


What will be the output of the program?


class Happy extends Thread
{
final StringBuffer sb1 = new StringBuffer();
final StringBuffer sb2 = new StringBuffer();
public static void main(String args[])
{
final Happy h = new Happy();
new Thread()
{
public void run()
{
synchronized(this)
{
h.sb1.append("A");
h.sb2.append("B");
System.out.println(h.sb1);
System.out.println(h.sb2);
}
}
}.start();
new Thread()
{
public void run()
{
synchronized(this)
{
h.sb1.append("D");
h.sb2.append("C");
System.out.println(h.sb2);
System.out.println(h.sb1);
}
}
}.start();
}
}
Options:
A .  ABBCAD
B .  ABCBCAD
C .  CDADACB
D .  Output determined by the underlying platform.
Answer: Option D

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.



Was this answer helpful ?
Next Question

Submit Solution

Your email address will not be published. Required fields are marked *

Latest Videos

Latest Test Papers