Wednesday 20 February 2013

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

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

Choices:
a. Prints : MyThread: start() followed by MyRunnable:run()
b. Prints : MyThread: run() followed by MyRunnable:start()
c. Prints : MyThread: start() followed by MyRunnable:start()
d. Prints : MyThread: run() followed by MyRunnable:run()
e. Compile time error
f. None of the above


Answer:-
A is the correct choice.
In the above code there is not any compilation error.
Thus choice E is incorrect.
Inside main() method, objects of MyThread and MyRunnable class are created followed by creation of Thread with object of MyRunnable class.
Note that MyThread class extends Thread class and overrides the start() method of the Thread class.
Thus on execution of "myThread.start()" statement, the start() method of the MyThread class will be executed and as a result "MyThread:start()" will be printed.
Had the start() method not there in MyThread class, the start() method of the Thread class would be called which in turn would call the run() method of the MyThread class.
On execution of "thread.start();", the start() method of the Thread class would be called which in turn will call the run() method of the class which is passed to Thread constructor (i.e. MyRunnable class). Thus "MyRunnable:run()" will be printed out.
Thus choice A is correct.

No comments:

Post a Comment