Originally posted by Abhi vijay:
Source:http://www.danchisholm.net/oct1/topic/section7/threads1.html
Can anyone explain me the flow of this program,i am not able to figure out???
class A implements Runnable {
public void run() {System.out.print(Thread.currentThread().getName());}
}
class B implements Runnable {
public void run() {
new A().run();
new Thread(new A(),"T2").run();
new Thread(new A(),"T3").start();
}}
class C {
public static void main (String[] args) {
new Thread(new B(),"T1").start();
}}
Answer: T1T1T3
The main program calls a new thread call T1 which calls the run method.
new A().run();
new Thread(new A(),"T2").run();
The above two calls doesnot create a new thread, they simply call run()(over here run is treated like any other function, so a new thread will not be created)
So the line
System.out.print(Thread.currentThread().getName() prints the name of the current thread which is T1
A new thread is created only when you call start().
The following line
new Thread(new A(),"T3").start();
Creates a new thread and sets its name as "T3"
Hence the output is T1T1T3