二次调用Thread类的start()方法会怎样
这个一般会出现在面试中,面试官会问的,那我门来看看Thread类的start(),看看它源码
/**
* 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();
/* 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 */
}
}
}
我们首先来翻译下它的注释
使该线程开始执行;Java虚拟机,调用该线程的run方法
然后再看看start()方法的执行流程是什么
先判断threadStatus这个变量是不是等于0,不等于0就抛出异常,然后加入线程组,再就是调用start0()方法,start0()是native层的方法,并没有在Java层实现,那么threadStatus变量是在什么时候进行赋值了呢?
在Thread类找了threadStatus所在用的地方都没有给threadStatus变量赋值,那就说明了JVM虚拟机在内层已经给他进行了赋值操作.
threadStatus的状态修改由底层的C++代码实现,而threadStatus的状态值变化对JVM是可见的,但是在Java里无法看到threadStatus改变的具体实现方式
总结
1.检查线程状态,只有NEW状态下的线程才能继续,否则会抛出IllegalThreadStateException(在运行中或者已结束的线程,都不能再次启动,详见CantStartTwice10类)
2.被加入线程组
3.调用start0()方法启动线程
注意点:
start方法是被synchronized修饰的方法,可以保证线程安全;
由JVM创建的main方法线程和system组线程,并不会通过start来启动