Java Programming - Java.lang Class - Discussion
Discussion Forum : Java.lang Class - Finding the output (Q.No. 26)
26.
What will be the output of the program?
public class Test
{
public static void main(String[] args)
{
final StringBuffer a = new StringBuffer();
final StringBuffer b = new StringBuffer();
new Thread()
{
public void run()
{
System.out.print(a.append("A"));
synchronized(b)
{
System.out.print(b.append("B"));
}
}
}.start();
new Thread()
{
public void run()
{
System.out.print(b.append("C"));
synchronized(a)
{
System.out.print(a.append("D"));
}
}
}.start();
}
}
Answer: Option
Explanation:
It gives different output while executing the same compiled code at different times.
C:\>javac Test.java C:\>java Test ABBCAD C:\>java Test ACADCB C:\>java Test ACBCBAD C:\>java Test ABBCAD C:\>java Test ACBCBAD C:\>java Test ACBCBAD C:\>java Test ABBCAD
Discussion:
11 comments Page 1 of 2.
Venkata said:
1 decade ago
ABBCAD is the output
Sundar said:
1 decade ago
@Venkata
Execute the code multiple times, you will get different output.
Execute the code multiple times, you will get different output.
Sreya said:
1 decade ago
Can anyone tell me why the output is undetermined. Each thread have their own run method. Then why will thread 1 go thread 2 run() ?
VJ'S said:
1 decade ago
Hi sreeya time slicing is done at OS Level.Its not guaranteed that which thread excutes when but only guarantees that two threads execute independently
Arnold villasanta said:
1 decade ago
Unrelated sync methods.. run() method executed based on JVM's mechanism of handling process.
Suresh said:
1 decade ago
ABBCAD is coming.
Arjun shah said:
10 years ago
But here synchronized keyword is used so is it possible that it will give multiple output?
Mukund said:
7 years ago
According to me, it should be ABBCAD.
Mukund said:
7 years ago
According to me, it should be ABBCAD.
Subha said:
7 years ago
Actually, in thread we can't able to predict the output that's why it is indeterminate simple.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers