• Post Reply Bookmark Topic Watch Topic
  • New Topic

How does the JVM know which run() to call

 
Srinu Nanduri
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following code :

class A implements Runnable
{
public void run()
{
// doSomeThing();
}
}

public class ThreadDemo
{
public static void main(String args[])
{
Thread thread = new Thread(new A());
thread.start();
}
}

Now, when the thread.start() is called, how does the JVM know to call the run() method of the class A but not its own run() method [Thread class implements Runnable.]
 
Henry Wong
author
Sheriff
Posts: 22542
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now, when the thread.start() is called, how does the JVM know to call the run() method of the class A but not its own run() method [Thread class implements Runnable.]


The new thread will call the run() method of the Thread object... If you override the run() method (by extending the Thread class), then it will call your run() method.

In your example, you didn't override the run() method, so it will call the original run() method. This run() method will check an instance variable for a runnable object, place there by the constructor. And if it exists, it will call the run() method of the runnable object.

Henry
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What Henry said.

Take a look at the source code of the Thread class (it comes with the JDK). In JDK 1.4, Thread.run() is implemented as



where "target" is the runnable provided in the constructor.
 
Srinu Nanduri
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Henry & Ilza,

Thanks a lot for your replies.
I now understood it well.

Will note this down.

Srinu
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!