• Post Reply Bookmark Topic Watch Topic
  • New Topic

Calling Thread's run V/s Runnable's run

 
Mandy Singh
Greenhorn
Posts: 23
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Can anyone please answer this:

Thread is a class which implements the runnable interface, so we override the run() method when we extend the Thread class and then call the start() method to actually run the thread. If I dont call the start() method and directly call run(), it will still execute ( without any "thread-ness" ). This part is perfectly clear to me. I overrode the run() method of the Thread class, so if the Thread instance calls - run(), it will execute the run() method that I defined.

Thread t1 = new MyThread() ; // Here, Thread is the superclass and its reference variable is pointing to a subclass - MyThread and calling its run method.

This is fine, as a proper linkage is established.

Now...
In case of implementing Runnable, I would pass the Runnable object to the Thread object's constructor and I am still able to call the run() method directly on the Thread instance.

How is the linkage established in the second case. How am I able to call run() directly using the Thread's instance ?

The answer to this question might be very simple... but am not able to think of it right now :-)

Please Help.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mandy. Welcome to The Ranch!

By default, the run() method of Thread calls the run() method of the Runnable that is passed into it.

I haven't looked at the source code, and there are probably other more complicated things going on, but the arrangement could be something like this:

Does that make sense?
 
Paul Clapham
Sheriff
Posts: 21889
36
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The run() method is a public method. Why shouldn't you be able to call it? The rules of Java say that anything can call public methods; run() is a public method; therefore anything can call the run() method.
 
Mandy Singh
Greenhorn
Posts: 23
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Matthew, now i understand it very clearly. Thanks.

Paul, i know that run() is a public method but I was just trying to understand how the Thread object is linked to the Runnable Object ( that we are able to call the runnable's run() using the Thread object directly). Anyway, thanks for your help.

:-)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!