• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

doubt in Threads

 
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

In the below code

class Threader extends Thread
{
public void run()
{
System.out.println("In Threader");
}
}
class Pooler extends Thread
{
public Pooler(){ }

public Pooler(Runnable r)
{
super(r); //1
}
public void run()
{
System.out.println("In Pooler");
}
}
public class Threadovr
{
public static void main(String[] args)
{
Threader t = new Threader();
Thread h = new Pooler(t); //2
h.run(); //3
h.start();// 4

}
}
as per my knowledge when we call start() and run() and target runnable object is specified then the run() of the target runnable object should be called in this case we are passing t as target runnable object then Threader class's run() should be called and it should print "In Threader".

But in the above code either i call start() or run() in both cases it will print "In Pooler" even though the target runnable object is of type Threader can any one please explain me what is the logic behind it.

Thanks
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For the first it is clear why this happens - you have a variable 'h' which refers to a Pooler object and you directly call the method 'run()', so then ofcourse you see "In Pooler".

For the second case: What you describe (the 'run()' in the target runnable is called) only happens when you do not override the run() method of class Thread. But you did override it in your class Pooler.

The reason: The run() method in class Thread is what normally calls the run() in the target.

(A tip: When you post source code on JavaRanch, please use code tags, so that the forum will properly format the source code, which makes it easier to read).
 
Chandra shekar M
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the reply
reply
    Bookmark Topic Watch Topic
  • New Topic