aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes question from Dan's on thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "question from Dan Watch "question from Dan New topic
Author

question from Dan's on thread

sanjana narayanan
Ranch Hand

Joined: Nov 25, 2003
Posts: 142
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

Joined: Aug 13, 2003
Posts: 39

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: question from Dan's on thread