在JDK中Thread类的源码中有个方法:
public void run() {
if (target != null) {
target.run();
}
}其中target是Thread类的一个成员变量,当我们创建一个线程的时候:
class TheadTest extends Thread{
public void run(){
System.out.println("Thread Test");
}}
当调用start()启动线程的时候,TheadTest线程怎么就知道调用target的run()方法呢,我们也没有给target成员变量赋值啊?
请问这是为什么啊?高手解决一下啊,我哪里理解的有问题啊?
public void run() {
if (target != null) {
target.run();
}
}其中target是Thread类的一个成员变量,当我们创建一个线程的时候:
class TheadTest extends Thread{
public void run(){
System.out.println("Thread Test");
}}
当调用start()启动线程的时候,TheadTest线程怎么就知道调用target的run()方法呢,我们也没有给target成员变量赋值啊?
请问这是为什么啊?高手解决一下啊,我哪里理解的有问题啊?
/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
* <p>
* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see #run()
* @see #stop()
*/
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();
group.add(this);
start0();
if (stopBeforeStart) {
stop0(throwableFromStop);
}
}
* If this thread was constructed using a separate
* <code>Runnable</code> run object, then that
* <code>Runnable</code> object's <code>run</code> method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of <code>Thread</code> should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
public void run() {
if (target != null) {
target.run();
}
}
if (target != null) {
target.run();
}
}
class TheadTest extends Thread{
public void run(){
System.out.println("Thread Test");
}}你的TheadTest 已经覆盖了JDK中Thread.run方法的实现了,所以调用new ThreadTest().start()时候所调用的run方法已经是你的代码,不会再调用到了 if (target != null) {
target.run();
}了
通过native方法start0启动 都是调用Thread.run() 除非自建Thread类中有覆盖run方法