线程的生命周期和start方法
线程的生命周期如下
在new Thread()后,线程并没有真正启动,只有在调用start方法后,才会成为一个线程。但是线程并不会立即执行,它处于可执行状态,即runnable状态,等待cpu的调度。当被分配到cpu执行权,就到了running状态。在running的过程中,如果sleep或者等待锁,就会处于blocked状态。被block后,不能立即进入running状态,只能回到runnable状态。同时处于running中的线程,也会进入runnable状态。这几种状态都能进入终结状态。
start
public void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
Throws:
IllegalThreadStateException - if the thread was already started.
See Also:
run(), stop()
文档中对start方法的描述,调用start后会导致产生一个新的线程,一个线程不能调用两次start().
总结一下:
- Java程序的main方法是一个线程,在被JVM启动时调用,线程名称是main
- 实现一个线程,必须创建Thread实例,重新run方法,并调用start方法
- 在JVM启动后,实际上有多个线程,但至少有一个非守护线程
- 当调用一个线程的start方法,此时至少有2个线程,一个是调用start方法的线程,另一个是执行run方法的线程
- 线程的生命周期分为new,runnable,running,blocked,terminated几种状态