多次start一个线程会怎么样
答案是:java.lang.IllegalThreadStateException
源码如下
/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>线程被执行,JVM调用run方法
* 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.多次调用start方法启动一个线程是非法的
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already已经启动的线程再次start,异常
* 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)//状态校验 0:NEW 新建状态
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();//调用native方法执行线程run方法
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 */
}
}
}
group.add(this),把当前线程添加进线程组,源码如下:
/**
* Adds the specified thread to this thread group.
*
* <p> Note: This method is called from both library code
* and the Virtual Machine. It is called from VM to add
* certain system threads to the system thread group.
*
* @param t
* the Thread to be added
*
* @throws IllegalThreadStateException
* if the Thread group has been destroyed
*/
void add(Thread t) {
synchronized (this) {
if (destroyed) {//线程组状态校验
throw new IllegalThreadStateException();
}
if (threads == null) {
threads = new Thread[4];//初始化长度为4的Thread数组
} else if (nthreads == threads.length) {//数组满了就扩容2倍
threads = Arrays.copyOf(threads, nthreads * 2);
}
threads[nthreads] = t;//新线程t添加进数组
// This is done last so it doesn't matter in case the
// thread is killed
nthreads++;//线程数加1
// The thread is now a fully fledged member of the group, even
// though it may, or may not, have been started yet. It will prevent
// the group from being destroyed so the unstarted Threads count is
// decremented.
nUnstartedThreads--;//未启动线程数-1
}
}