Home / Java Programming / Threads :: Discussion

Discussion :: Threads

  1. What will be the output of the program?

     public class ThreadDemo 
     {    
         private int count = 1;   
         public synchronized void doSomething()    
         {        
             for (int i = 0; i 10; i++)                         
                 System.out.println(count++);      }    
    public static void main(String[] args)      {       
         ThreadDemo demo = new ThreadDemo();             
         Thread a1 = new A(demo);          
         Thread a2 = new A(demo);          
         a1.start();  
         a2.start();  
        } 
      }
      class A extends Thread
      {
          ThreadDemo demo;   
          public A(ThreadDemo td)    
          {      
             demo = td;  
          }      
          public void run()     
          {       
             demo.doSomething();    
          }      
       } 
    

  2. A.

    It will print the numbers 0 to 19 sequentially

    B.

    It will print the numbers 1 to 20 sequentially

    C.

    It will print the numbers 1 to 20, but the order cannot be determined

    D.

    The code will not compile.

    View Answer

    Workspace

    Answer : Option B

    Explanation :

    You have two different threads that share one reference to a common object.

    The updating and output takes place inside synchronized code.

    One thread will run to completion printing the numbers 1-10.

    The second thread will then run to completion printing the numbers 11-20.


Be The First To Comment