Thread start 和 run 方法源码如下
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 */
}
}
}
@Override
public void run() {
if (target != null) {
target.run();
}
}
调用时
Thread thread = new Thread();
thread.start();
对应线程状态
NEW:当通过关键词 new 创建一个 Thread 对象时,线程进入 NEW 状态,这时线程的 threadState 为 0。
RUNNABLE:当调用 start 方法时,线程进入 RUNNABLE 状态,线程会被加入一个 ThreadGroup 中去,线程如果再次被调用 start 方法,会抛出 IllegalThreadStateException 异常;在这里 JVM 会执行线程的 run 方法,即被 JNI 方法 start0() 调用。
TERMINATED:如果一个线程生命周期结束,也不能回到 RUNNABLE 状态,它的生命周期已经结束,再次调用 start 方法是不允许的,在这里同样会抛出 IllegalThreadStateException 异常。
下面验证两个不同抛出 IllegalThreadStateException 异常的场景
1) start方法重复调用抛出 IllegalThreadStateException 异常
执行代码
Thread thread = new Thread() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
thread.start();
发现抛出异常。
2) 线程生命周期结束,再次调用 start 方法抛出 IllegalThreadStateException 异常
执行代码
Thread thread = new Thread() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
TimeUnit.SECONDS.sleep(2);
thread.start();
发现抛出异常。