I was looking a small example on Threads.For creating Threads we can do in 2 ways either by implementing Runnable
interface or by extending Thread.I used the 1st way
package test;
public class test implements Runnable{
public static void main(String args[])
{
test t=new test();
t.run();Thread th=Thread.currentThread();
th.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("hi");
}
}
My doubt is when we are calling th.start();
then run()
is called.I want to know how.I thought internally there start()
may be calling run()
so I looked in the documentation of Thread class
The following is the start()
declaration in Thread class
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
As you can see inside start()
,run()
is not called but when we are calling th.start()
then automatically overriden run()
is called.Can anybody please throw some light in this
The mechanism whereby the run
method is invoked on a new thread is extralinguistic: it cannot be represented in terms of Java code. This is the crucial line in the start
method:
start0();
start0
is a native method whose invocation will:
run
method to be invoked on that thread. Thread th=Thread.currentThread();
th.start();// its call run method automatically
if you call direct run method with class object than its treat as a normal method not thread method
start() method of Thread class is used to start a newly created thread. It performs following tasks: A new thread starts(with new callstack). The thread moves from New state to the Runnable state. When the thread gets a chance to execute, its target run() method will run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With