• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

question from Dan's on thread

 
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
We cannot change unless we survive, but we will not survive unless we change. Evolving tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic