What is the result of attempting to compile and run the program? a. Prints: T1T1T1 b. Prints: T1T1T2 c. Prints: T1T2T2 d. Prints: T1T2T3 e. Prints: T1T1T3 f. Prints: T1T3T3 g. Compile-time error h. Run-time error i. None of the above
the answer is( e.)Prints: T1T1T3 Please explain me why ?
Edited by Corey McGlone: Added CODE Tags [ September 07, 2005: Message edited by: Corey McGlone ]
starts a new thread named T1, and this start invokes run method of class B.
class B's run method is : new A().run(); <== call class A's run method <== and class A's run method prints the <== name of current executing thread <== and currently executing thread is T1
new Thread(new A(),"T2").run(); <== This statement is creating a new Thread <== and calling run method of Thread directly <== Note : run method called in this statement <== none of the run methods coded here, but <== the one coded in java.lang.Thread and <== which calls the run method of Runnable <== passed in the constructor and this is <== A's run method. ( This statement calls <== run method directly so no new thread <== is spawned in statement. ) So, A's run <== method still prints T1 as that is the only <== thread still executing, so T1 is printed <== again new Thread(new A(),"T3").start(); <== This spawns a new thread named T3 and by now <== it should be clear why T3 is printed