Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread question

 
saima kanwal
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator





The above code is from Khalid Mughal . At line 1 the run method of Extender is executed. According to me the run of Class A1 should run because the constructor of Extender with argument invokes the super(runnable) so the run of runnable should run .

the output is Extender Extender Implementer
but i think the output should be Implementer Extender Implementer

can anyone explain why the run method of A1 is not invoked at line 1?

 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually this happens because the start method of Thread class calls the run method of the Thread class (or any subclasses like your Extender class - polymorphism). It is the responsibility of the run method to call the run method of the runnable object. The Thread class is implemented something like this

So for line 1 to work like line 3, the Extender class will have to be modified like this
 
saima kanwal
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks ankit
 
Weiheng Zhang
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

instance of Extender gets |Extender|
instance of A1 gets |Implementer|
That's correct, but the point is that there are 3 threads, the order is unpredictable for it's controlled by JVM rather than the order of source code, if run again, you may see different results.
 
Janki Shah
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ankit Garg wrote:Actually this happens because the start method of Thread class calls the run method of the Thread class (or any subclasses like your Extender class - polymorphism). It is the responsibility of the run method to call the run method of the runnable object. The Thread class is implemented something like this

So for line 1 to work like line 3, the Extender class will have to be modified like this

Hi Ankit, I tried doing what you are saying. but still it prints the same. It does not run the method from Implementer.here is the code,
can you also explain when which method runs?I am very confused.

when I pass different objects to the Thread constructor, it executes the run method of that object meaning new Thread(new MyThread()).start(); calls executes run method of MyThread class.
Can any one please explain, what is the rule ?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic