Ans is T1T1T3 In the main method, new Thread(new B(),"T1").start(); how does it know which run() to invoke?? that of class A or that of class B? Also how did the control go to new Thread(new A(),"T3").start(); Edited by Corey McGlone: Added CODE Tags [ March 17, 2004: Message edited by: Corey McGlone ]
Also I understand that a new thread is started only with the start() method. therefore the stmt in main starts a thread "T1", which is printed because the run() in class A is invoked?? After that, in class B: new A().run(), does not start a new thread, but only invokes the method run(), Thread.currentThread returns "T1" new Thread(new A(),"T2").run();, once again calls the run() method in class A without creating a new thread and Thread.currentThread returns "T1"
new Thread(new A(),"T3").start();, here the start() invokes the run() in class A starting a new thread "T3" which gets printed. Am i right? or is my logic in understanding this totally wrong? please help!!
Shouldn't this invoke the run() method in the class Thread?? Or it's somehow "short-circuited" to invoke the new A().run() (I mean it obviously is but I'd appreciate a more technical explanation if someone can give it )?
The thing is that it's not quite clear, because after this
I indeed have a brand new Thread object - but nevertheless is not "true" thread - it still is NOT a separate thread of execution. So what's the "thread" in the quote - Thread object or a real thread of execution? Obviously it's a bit vague. Anyways, thanks for your time.
The key to understanding that line is that by invoking the run() method directly, we are not creating a new thread of execution. Rather, we're just invoking a method like any other. In that case, when you invoke the method Thread.currentThread(), you are returned a reference to the thread that invoked the run() method - in this case, that thread is "T1." When you invoke the start() method, a new thread is spawned and that thread invokes the run method. Therefore, when you invoke Thread.currentThread(), you obtain a reference to that brand new thread, not the one that invoked the start() method. I hope that helps, Corey
, here you are specifying that Runnable implementation B is the class whose run method should be invoked. The thread name is specified as "T1". 2) B's run method is like :
Keep in mind once you started B, the current thread name is T1. Untill another thread is started which happens only in line 3. line 1 : calls the run method of A. Current thread = T1 => output T1 line 2 : calls the run method of A keep in mind this is not same as starting the thread. Current thread = T1 (still) => output T1 line 3 : creates a new Thread passing runnable A and sets the Thread name to T3, and starts it. Now the current thread is this new thread with name T3. => T3. Hope that helps. Thanks, Rumpa [ March 17, 2004: Message edited by: Rumpa Giri ] [ March 17, 2004: Message edited by: Rumpa Giri ]