Menu
Topics Index
...
`

Thread


If you need explanation Read this topic

If you need Answer Take test on this topic

Thread
What will be the output of the following 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.print(h.sb1);
                    System.out.print(h.sb2);
                }
            }
        }.run();
        new Thread() {
            public void run() {
                synchronized (this) {
                    h.sb1.append("D");    h.sb2.append("C");
                    System.out.print(h.sb2);
                    System.out.print(h.sb1);
                }
            }
        }.start();
    }
}

A. ABDCAD
B. ABCBCAD
C. CDADACB
D. ABBCAD
E. Output can not be determined
F. Compilation Error or Runtime Error
Topic: What is Multitasking and Multithreading?

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

D
run() will be executed on calling thread + first thread will obtain lock on object second thread (synchronized on same object) has to wait. now,
sb1 A
sb2 B
After execution of 2nd thread
sb1 AD
sb2 BC

Posted by Tushar Ghude    2014-07-28 14:10:25


Ans is F..StringBuffer rfnrces is fainl so we cant modify

Posted by Uday Kumar    2014-07-28 14:26:30


ans a.
1st thread prints AB.
2nd prints BCAD

Posted by Maheshwari Natarajan    2014-07-28 15:30:45


^i didnt notice that before but
options A and D are exactly the same :D trick question

Posted by Tushar Ghude    2014-07-28 16:01:56


f.........

Posted by Arul Palanisamy    2014-07-28 17:27:07


Congratulations Tushar Ghude. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-07-29 04:36:21


© meritcampus 2019

All Rights Reserved.

Open In App