Home / Java Programming / Threads :: Discussion

Discussion :: Threads

  1. What will be the output of the program?

    class MyThread extends Thread 
     {    
       MyThread()    
       {       
            System.out.print(" MyThread");         
       }  
       public void run()  
       {       
            System.out.print(" bar"); 
        }    
        public void run(String s)     
        {      
             System.out.println(" baz"); 
        } 
      }
      public class TestThreads  
      {   
         public static void main (String [] args)     
         {
             Thread t = new MyThread()                 
              {   
                 public void run()                
                 {                              
    
                   System.out.println(" foo");             
                  }        
               };        
               t.start();   
           } 
        } 
    

  2. A.

    foo

    B.

    MyThread foo

    C.

    MyThread bar

    D.

    foo bar

    View Answer

    Workspace

    Answer : Option B

    Explanation :

    Option B is correct because in the first line of main we're constructing an instance of an anonymous inner class extending from MyThread. So the MyThread constructor runs and prints "MyThread". The next statement in main invokes start() on the new thread instance, which causes the overridden run() method (the run() method defined in the anonymous inner class) to be invoked, which prints "foo"


Be The First To Comment