Wednesday 27 February 2013

28. What will happen when you attempt to compile and run the following code?

28.  What will happen when you attempt to compile and run the following code?



Choices:
a.The above code in its current condition will not compile.
b. In order to make the MyThread class prints "mt1" (100 times) followed by
"mt2" (100 times), mt1.join(); can be placed at //XXX position.
c. In order to make the MyThread class prints "mt1" (100 times) followed by
"mt2" (100 times), mt1.sleep(100); can be placed at //XXX position.
d. In order to make the MyThread class prints "mt1" (100 times) followed by
"mt2" (100 times), mt1.run(); can be placed at //XXX position.
e. In order to make the MyThread class prints "mt1" (100 times) followed by
"mt2" (100 times), there is no need to write any code.

Answer:-
A and B are correct. In its current condition, the above code will not compile as "InterruptedException" is never thrown in the try block. The compiler will give following exception: "Exception java.lang.InterruptedException is never thrown in the body of the corresponding try statement." Note that calling start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be called. Depending on the operating system and other running threads, the thread on which start is called will get executed. After making the above code to compile (by changing the InterruptedException to some other type like Exception), the output can't be predicted (the order in which mt1 and mt2 will be printed can't be guaranteed). In order to make the MyThread class prints "mt1" (100 times) followed by "mt2" (100 times), mt1.join() can be placed at //XXX position. The join() method waits for the Thread on which it is called to die. Thus on calling join() on mt1, it is assured that mt2 will not be executed before mt1 is completed. Also note that the join() method throws InterruptedException, which will cause the above program to compile successfully. Thus choice A and B are correct. 
==

public class MyThread extends Thread
{
  String myName;

                MyThread(String name)
  {
                  myName = name;
                }

  public void run()
  {
  for(int i=0; i<100;i++)
  {
  System.out.println(myName);
  }
  }

  public static void main(String args[])
  {
  try
  {
                                         MyThread mt1 = new MyThread("mt1");
                                         MyThread mt2 = new MyThread("mt2");
  mt1.start();
                                                // XXX
  mt2.start();
  }
                                 catch(InterruptedException ex)
  {
  }
  }
}

 

No comments:

Post a Comment