我正在寻找一个关于线程的小例子。为了创建线程,我们可以通过两种方式来实现:Runnable
接口或通过扩展Thread。我使用第一种方式
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");
}
}
我的疑问是当我们打电话时th.start();
then run()
被称为。我想知道如何。我内心想start()
可能正在打电话run()
所以我查看了 Thread 类的文档
以下是start()
Thread类中的声明
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 */
}
}
}
正如你在里面看到的start()
,run()
没有被调用,但是当我们调用时th.start()
然后自动覆盖run()
被称为。有人可以解释一下吗
其机制是run
在新线程上调用方法是语言外的:它不能用Java代码表示。这是关键的一行start
method:
start0();
start0
是一个本机方法,其调用将:
- 导致创建一个新的本机执行线程;
- 导致
run
要在该线程上调用的方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)