源码分析
//start方法才是启动一个线程 run()是同步执行一次
new Test0().start();
//来到Thread类里面
//查看当前线程状态是否为0
public synchronized void start() {
//这个threadStatus为线程的状态码不为0时,当该线程已经起来了则抛出非法线程状态异常
if (threadStatus != 0)
throw new IllegalThreadStateException();
//将前线程加入到线程组
group.add(this);
boolean started = false;
try {
//调用start0()方法,启动线程
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 */
}
}
}
//接下来发现是native方法
private native void start0();
启动线程
start0()方法
private native void start0();
/**
* 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)
*/
@Override
public void run() {
if (target != null) {
target.run();
}
}
native方法
native方法,该方法是jvm底层调用的,执行传入的Thread的run()方法。启动线程。至此创建线程完成。
上面的native方法,最终调用到JVM thread.cpp中,然后JVM 根据不同的操作系统会调用的对应OS create一个线程,并且该方法会告诉CPU start了一个线程,然后在cpu调度算法中执行此线程时会回调到JVM中,最终调用thread 中的run方法,也就是我们手写的代码,线程开始执行