Home / Java Programming / Threads :: Discussion

Discussion :: Threads

  1. What will be the output of the program?

    public class Test 
     {    
        public static void main (String [] args)      
        {      
           final Foo f = new Foo();         
           Thread t = new Thread(new Runnable()      
           {       
              public void run()      
              {             
                  f.doStuff();       
              }        
           });      
           Thread g = new Thread()       
           {        
              public void run()           
              {        
                  f.doStuff();        
              }     
           };    
           t.start();      
           g.start();  
       } 
     } 
     class Foo 
     {   
           int x = 5; 
           public void doStuff()    
           {        
                if (x 10)          
                {            
                  // nothing to do               
                  try           
                  {          
                      wait();                 
                } catch(InterruptedExcepx) { }         }     
    else        
    {          
        System.out.println("x is " + x++);                
        if (x >= 10)        
        {            
                notify();     
            }        
          }     
        } 
     } 
    

  2. A.

    The code will not compile because of an error on notify(); of class Foo.

    B.

    The code will not compile because of some other error in class Test.

    C.

    An exception occurs at runtime.

    D.

    It prints "x is 5 x is 6".

    View Answer

    Workspace

    Answer : Option C

    Explanation :

    C is correct because the thread does not own the lock of the object it invokes wait() on. If the method were synchronized, the code would run without exception.

    A, B are incorrect because the code compiles without errors.

    D is incorrect because the exception is thrown before there is any output.


Be The First To Comment