Reputation: 59
In the code given below I have passed the Temp
class object's reference id inside the Thread
constructor call which would be catched by thread class's constructor in Runnable
type reference variable. so I want to ask that is there any code inside that Thread
class constructor which tells the JVM that this particular class's run()
method is to be executed when a thread is created.
class Temp implements Runnable
{
public void run()
{
System.out.println("Hello from a thread!");
}
public static void main(String args[])
{
(new Thread(new Temp())).start();
}
}
Upvotes: 1
Views: 363
Reputation: 719336
What happens (in general) is this.
Thread.start()
method allocates the stack, and so on.Thread.run()
method.Thread.run()
, then your override run()
method is called.
run()
method implemented by Thread
itself is called.
Thread.run()
method checks to see if the Thread
instance has a Runnable
instance.Thread.run()
calls the run()
method on the Runnable()
.Thread.run()
method simply returns.Thread.run()
method returns (or terminates abnormally), the start()
method marks the Thread
as no longer alive, and releases the stack and dismantles other stuff associated with the Thread object.Is there any code inside that Thread class constructor which tells the JVM that this particular class's run() method is to be executed when a thread is created.
Not exactly. The constructor stores the Runnable
in a private variable, and the Thread.run()
method tests the private variable ... if Thread.run()
hasn't been overridden.
Upvotes: 0
Reputation: 70949
Inside the thread.start()
method, the thread calls runnable.run()
.
A simple way of how this could work but really, it's not done this way due to this example not creating a new thread, is
public class Thread {
private Runnable runnable;
public Thread(Runnable runnable) {
this.runnable = runnable;
}
public void start() {
if (runnable != null) {
runnable.run();
}
}
}
Then when you call:
new Thread(this).start();
A new Thread will be created, assigning the Runnable this to the inner private member. Later, after the object is created, start()
will be called on the object, which will look up the private runnable
member, and call it's run()
method.
Upvotes: 1
Reputation: 13733
Thread
's start
method calls the run
method of the object you pass as an argument to the constructor. Since you pass an object of class Temp
, Temp
's run method will be called.
Upvotes: 0
Reputation: 179592
You passed in a Temp
object as the Thread
's Runnable
. Thread.start
will call the run
method of its Runnable
, so Temp.run
is going to get called.
Upvotes: 0
Reputation: 469
start() is the command to begin using the thread that you specified in method run(). Whenever start() is called, it will execute code in the run() method.
Upvotes: 0