线程一个完整的生命周期要经历如下五种状态:
上面的API文档是说,当我们调用线程的start方法时,JVM会调用当前线程的run()方法。这样就同时有两个线程在运行(当前线程和调用线程start()方法的线程)
此外,同一个线程不能调用start()方法两次,否则会报错,IllegalThreadStateException
。
(1)线程调用两次start()方法测试
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
System.out.println("hello");
});
thread.start();
thread.start();
}
输出结果:
(2)start()内部源码分析
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".
*/
//状态校验 0: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(); //调用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 */
}
}
}
调用start()后,线程会被放到等待队列,等待CPU调度,并不一定要马上开始执行,只是将这个线程置于可动行状态。然后通过JVM,线程Thread会调用run()方法,执行本线程的线程体。先调用start后调用run,这么麻烦,为了不直接调用run?就是为了实现多线程的优点,没这个start不行。
记住:多线程就是分时利用CPU,宏观上让所有线程一起执行 ,也叫并发。
原文:https://www.cnblogs.com/ch-forever/p/10747235.html