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(); 
    } 
}
ACCBAD
ABBCAD
CDDACB
Indeterminate output
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.

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

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() ?

Subha said:   7 years ago
Actually, in thread we can't able to predict the output that's why it is indeterminate simple.

Arnold villasanta said:   1 decade ago
Unrelated sync methods.. run() method executed based on JVM's mechanism of handling process.

Arjun shah said:   10 years ago
But here synchronized keyword is used so is it possible that it will give multiple output?

Sundar said:   1 decade ago
@Venkata

Execute the code multiple times, you will get different output.

Bidisha Paul said:   6 years ago
It is not the correct answer, according to me, it should be ACCBAD.

Mukund said:   7 years ago
According to me, it should be ABBCAD.

Mukund said:   7 years ago
According to me, it should be ABBCAD.

Venkata said:   1 decade ago
ABBCAD is the output


Post your comments here:

Your comments will be displayed after verification.