线程如何运行? [英] How Thread run starts?
问题描述
我在Threads.上看了一个小例子。为了创建线程我们可以通过实现 Runnable
接口或者通过扩展Thread.I使用第一种方式来做两种方式/ p>
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");
}
}
我怀疑的是我们打电话 th.start();
然后 run()
被调用。我想知道如何。我内心想到 start()
可能正在调用 run()
所以我查看了Thread类的文档
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
以下是Thread类中的 start()
声明
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 */
}
}
}
如你所见 start()
, run()
没有被调用但是当我们调用 th.start()
然后自动覆盖 run()
被调用。任何人都可以在这个中点亮一点
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
推荐答案
运行的机制
方法 extralinguistic :它不能用Java代码表示。这是 start
方法中的关键行:
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
是一个本机方法,其调用将:
start0
is a native method whose invocation will:
- 导致创建新的本机执行线程;
- 导致
运行
在该线程上调用的方法。
- cause a new native thread-of-execution to be created;
- cause the
run
method to be invoked on that thread.
这篇关于线程如何运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!