Originally posted by Chris Cairns:
Could someone explain to me why this code prints T1T1T3?
class A implements Runnable {
public void run() {System.out.print(Thread.currentThread().getName());}
}
class B implements Runnable {
public void run() { //2
new A().run();//3
new Thread(new A(),"T2").run();//4
new Thread(new A(),"T3").start();//5
}
}
class C {
public static void main (String[] args) {
new Thread(new B(),"T1").start();//1
}
}
There is a difference between a
Thread and a Thread of execution.
A thread is nothing but an instance of class Thread.
ex : Thread t = new Thread(Runnable target);
t is just like any other instance. It does not do anything.
However , a thread of execution is a bit different. Its the new thread spawned.
At line 1, you are creating a Thread of execution (because the start method is called). it searches for the run method of the passed Runnable target.
So the run method of B is executed.
now at line 3,
new A().run();//3 you are just calling the run method of an object of class A. You havent created a new thread.
You know in line 1 that the name of the thread created is T1.
so the thread that is executing run method of class A is T1. Hence first T1 is printed.
line 4 has the same logic because you are not creating a thread of execution but calling the run method of A using the present thread whose name is T1
line 5
new Thread(new A(),"T3").start();//5 by now, you know that start method creates a new thread of execution. The new thread of execution has the name T3. Hence the run method of class A prints the presently executing thread which is T3
Hence the result T1T1T3
I know its a clumsy explanation. but feel free to shoot your questions
Sri