Java Programming - Threads - Discussion

Discussion Forum : Threads - Finding the output (Q.No. 11)
11.
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(); 
    } 
}
ABBCAD
ABCBCAD
CDADACB
Output determined by the underlying platform.
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.

Discussion:
18 comments Page 2 of 2.

Madhu Sudhan Reddy said:   1 decade ago
I excuted this program output : ABBCAD

But you told - "Output determined by the underlying platform". Please explain.

Rahul said:   1 decade ago
If the data members are declared using final keyword how can one modify the stringBuffer object could somebody please explain.

Yuga said:   1 decade ago
Hi,

If it is the case. Then, what is the use of synchronized block. Why it is needed?

Please help to understand.

Thank you.

Akshay said:   1 decade ago
@Rahul.

I have the same exact question.

How can you modify the stringbuffer if it is declared with the "final" keyword?

Kannan said:   1 decade ago
I excuted this program output : ABBCAD

But you told - "Output determined by the underlying platform". Please explain.

Jamil said:   10 years ago
If we use multi-thread with a Synchronization block it will produce a same result.

Reha said:   1 decade ago
A
B
BC
AD

I have also got this output.

Shakeer Hussain said:   9 years ago
I got the output like:

A
B
BC
AD


Post your comments here:

Your comments will be displayed after verification.