This week's book giveaways are in the Scala and Android forums.
We're giving away four copies each of Machine Learning Systems: Designs that scale and Xamarin in Action: Creating native cross-platform mobile apps and have the authors on-line!
See this thread and this one for details.
Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

java threads  RSS feed

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the following code gives 1 as output
please is there any body can explin the logic and correct thinking pattern to get that answer

class B extends Thread {
B(){}
B(B a){}
public void run(){
System.out.println("1");
}
}


class A extends B {
A(){}
A(B a){}
public void run(){
System.out.println("2");

}

public static void main( String as[]){

Thread a =new B (new A());

a.start();


}
}
 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

B extends Thread and A extends B. Hence, A IS-A B and B IS-A Thread. When you say: Thread a = new B(new A());, JVM chooses Object B at runtime and constructs a new B. Since B's constructor can take a 'B' Object and A IS-A B, therefore the run() method of B is called and the output is 1.
 
Java Cowboy
Sheriff
Posts: 16083
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch. Please use code tags when you post code.
 
Sheriff
Posts: 9611
37
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Asanka this is because the internal implementation of the run method in Thread class. The internal implementation of Thread class looks like this




So when you use this code


The run method of Thread class is called and it calls the run method of MyRunnable class.

But in you code the run method of B will be called and it doesn't calls the run method of A class. Infact, it wastes the Runnable passed to it as a parameter

B(B a)
{//does nothing}

This constructor declaration should have been like this

B(Runnable r)
{
super(r);
}
 
Space pants. Tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!