Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

question from Dan's on thread

 
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
 
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.
 
This looks like a job for .... legal tender! It says so right in this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic