Threads

Q1: What will be the output of the program?
class Test116 
{ 
static final StringBuffer sb1 = new StringBuffer(); 
static final StringBuffer sb2 = new StringBuffer(); 
public static void main(String args[]) 
{ 
    new Thread() 
    { 
        public void run() 
        { 
            synchronized(sb1) 
            { 
                sb1.append('A'); 
                sb2.append('B'); 
            } 
        } 
    }.start(); 

    new Thread() 
    { 
        public void run() 
        { 
            synchronized(sb1) 
            { 
                sb1.append('C'); 
                sb2.append('D'); 
            } 
        } 
    }.start(); /* Line 28 */

    System.out.println (sb1 + ' ' + sb2); 
    } 
}

A
main() will finish in the middle of one thread.

B main() will finish in the middle of one thread.

C
main() will finish in the middle of one thread.

D Cannot be determined.

ANS:A -

main() will finish in the middle of one thread.

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. add this code after line 28: try { Thread.sleep(5000); } catch(InterruptedException e) { } and you have some chance of predicting the outcome.



img not found
img

For help Students Orientation
Mcqs Questions

One stop destination for examination, preparation, recruitment, and more. Specially designed online test to solve all your preparation worries. Go wherever you want to and practice whenever you want, using the online test platform.