线程状态
线程的状态和进程的状态基本上一摸一样,所以这里不详细的描述
线程状态转换图
新建状态:主线程创建了子线程,但没有发送start()消息
就绪状态:分配CPU就能执行
运行状态:正在运行
阻塞状态:线程进入阻塞队列,需要被唤醒才能进入就绪状态
- 调用sleep()方法
- 调用join()方法
- 发出I/O请求
- 调用wait()方法
死亡状态:
- 线程正常运行并退出run()方法
- 线程运行过程发生异常未处理
深入探讨线程状态
其实,Java在实现时,阻塞状态不止一个(因为造成阻塞的原因不只一个)。
A thread state. A thread can be in one of the following states:
- NEW
A thread that has not yet started is in this state.
- RUNNABLE
A thread executing in the Java virtual machine is in this state.
- BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
- WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
- TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
- TERMINATED
A thread that has exited is in this state.
第一个阻塞状态:BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
monitor lock这是后面要提到的同步监视器(也就是“锁”)。一个线程如果进入同步方法(或同步代码块)时,没有拿到锁,就会被阻塞,进入BLOCKED状态。
第二个阻塞状态:WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
一个线程不确定(indefinitely)地等待,也就是说,要阻塞多长时间是不确定地,需要等另一个线程地特定动作。
例如:一个线程调用wait()方法,这个线程被阻塞,这个线程的唤醒依赖于另一个线程调用notify()或notifyAll()方法。
第三个阻塞状态:TIMED_WAITING
在明确的等待时间里,等待另一个线程的唤醒。(即使没有线程唤醒,在一段时间过后也会被唤醒)
例如:调用带参数的wait()方法,即使不被另一个线程调用notify()方法唤醒,在一段时间后也会被唤醒。