Java Programming - Java.lang Class - Discussion

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(); 
    } 
}

[A]. ACCBAD
[B]. ABBCAD
[C]. CDDACB
[D]. Indeterminate output

Answer: Option D

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

Venkata said: (Jan 21, 2011)  
ABBCAD is the output

Sundar said: (Jan 21, 2011)  
@Venkata

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

Sreya said: (Jun 23, 2011)  
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: (Sep 17, 2012)  
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: (Aug 10, 2014)  
Unrelated sync methods.. run() method executed based on JVM's mechanism of handling process.

Suresh said: (Apr 29, 2015)  
ABBCAD is coming.

Arjun Shah said: (Jan 1, 2016)  
But here synchronized keyword is used so is it possible that it will give multiple output?

Mukund said: (Jan 6, 2019)  
According to me, it should be ABBCAD.

Mukund said: (Jan 6, 2019)  
According to me, it should be ABBCAD.

Subha said: (Feb 8, 2019)  
Actually, in thread we can't able to predict the output that's why it is indeterminate simple.

Bidisha Paul said: (Sep 21, 2019)  
It is not the correct answer, according to me, it should be ACCBAD.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.