Home / Java Programming / Threads :: Discussion

Discussion :: Threads

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

  2. A.

    ABBCAD

    B.

    ABCBCAD

    C.

    CDADACB

    D.

    Output determined by the underlying platform.

    View Answer

    Workspace

    Answer : Option D

    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.


Be The First To Comment