Home / Java Programming / Threads :: Discussion

Discussion :: Threads

  1. What will be the output of the program?

    public class SyncTest 
     {     public static void main (String [] args)    
           {     
              Thread t = new Thread()           
              { 
                 Foo f = new Foo();             
                 public void run()              
                 {                 
                    f.increase(20);             
                 }     
              };    
           t.start();     
            }
         } 
         class Foo 
         {   
            private int data = 23;   
            public void increase(int amt)      
            {  
                 int x = data;  
                 data = x + amt;    
            }
         } 
    

    and assuming that data must be protected from corruption, what€”if anything€”can you add to the preceding code to ensure the integrity of data?

     

  2. A.

    Synchronize the run method.

    B.

    Wrap a synchronize(this) around the call to f.increase().

    C.

    The existing code will cause a runtime exception.

    D.

    Synchronize the increase() method

    View Answer

    Workspace

    Answer : Option D

    Explanation :

    Option D is correct because synchronizing the code that actually does the increase will protect the code from being accessed by more than one thread at a time.

    Option A is incorrect because synchronizing the run() method would stop other threads from running the run() method (a bad idea) but still would not prevent other threads with other runnables from accessing the increase() method.

    Option B is incorrect for virtually the same reason as A€”synchronizing the code that calls the increase() method does not prevent other code from calling the increase() method.


Be The First To Comment