Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question from Dan's on thread

 
sanjana narayanan
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
This is a question from Dan's mock exam on the topic "threads"
class A implements Runnable {
public void run() {System.out.print(Thread.currentThread().getName());}
}
class B implements Runnable {
public void run() {
new A().run(); // is it a normal method call of class A
new Thread(new A(),"T2").run(); // doesn't create a new thread. what does it exactly do
new Thread(new A(),"T3").start(); // starts a new thread
}
}
class C {
public static void main (String[] args) {
new Thread(new B(),"T1").start(); // starts a new thread
}
}
The ans is T1T1T3. Pl. explain the code to me.
-Sanjana
 
Sagarika nair
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I interpret the above code as follows:
At line 4 a new thread instance is created in the main method (or main thread) and the start method is invoked.Now the thread T1 is in a runnable state and whenever it gets its turn at the JVM it invokes the run method of class B automatically b'cos the runnable target is class B in the thread constructor and a new thread of execution is started.
Now at line 1,the run method of class A is invoked as we would invoke a regular method,but this does not start a new thread of execution but just runs within the thread named T1 .So the run method of class A prints T1.
At line 2 also the same process happens b'cos we have not invoked start method, a new thread is not started and this still runs within the thread T1.So T1 is printed again.
Line 3 creates a new thread of execution named T3 since it calls the start method.So thread T3 is in runnable state and whenever it is ready ,it enters the run method of A since the runnable target is A and so T3 is printed.
Hence the result.
I hope that makes sense.If not correct me .
Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic