线程的6种状态以及转变:
java的线程一共6种状态。具体代码见:
java.lang.Thread.State
1 NEW
新建状态
Thread state for a thread which has not yet started.
线程还没有调用start的时候
2 RUNNABLE
可运行状态
Thread state for a runnable thread. A thread in the runnable
state is executing in the Java virtual machine but it may
be waiting for other resources from the operating system
such as processor.
调用start之后,jvm启动了这个任务,但是可能被其他资源占用线程变成WAITING
3 BLOCKED
阻塞状态
Thread state for a thread blocked waiting for a monitor lock.
A thread in the blocked state is waiting for a monitor lock
to enter a synchronized block method or
reenter a synchronized block method after calling
{@link Object#wait() Object.wait}.
线程被锁的时候,线程等待进去一个synchronized块方法或者可重入锁的时候
4 WAITING
等待状态
Thread state for a waiting thread.
A thread is in the waiting state due to calling one of the
following methods:
- {@link Object#wait() Object.wait} with no timeout< li>
- {@link #join() Thread.join} with no timeout< li>
- {@link LockSupport#park() LockSupport.park}< li>
< ul>
A thread in the waiting state is waiting for another thread to
perform a particular action.
For example, a thread that has called Object.wait()
on an object is waiting for another thread to call
Object.notify() or Object.notifyAll() on
that object A thread that has called Thread.join()线程调用object.wait thread.join LockSupport.park 的时候变成 WAITING
5 TIMED_WAITING,
时间等待状态
Thread state for a waiting thread with a specified waiting time.
A thread is in the timed waiting state due to calling one of
the following methods with a specified positive waiting time:
- {@link #sleep Thread.sleep}< li>
- {@link Object#wait(long) Object.wait} with timeout< li>
- {@link #join(long) Thread.join} with timeout< li>
- {@link LockSupport#parkNanos LockSupport.parkNanos}< li>
- {@link LockSupport#parkUntil LockSupport.parkUntil}< li>
< ul>
sleep 或者wait,join带时间参数等方法时
6 TERMINATED
终止状态
Thread state for a terminated thread.
The thread has completed execution.
线程执行完成 或者被中断的时候变成TERMINATED
TERMINATED;
状态流转图
线程创建出来就是new的状态。
start方法调用之后状态变成runnable,可以执行,如果cpu把时间片切过来就可以执行。
runnable执行完成则变成terminated,或者中断的时候。
runnable如果遇到有锁的方法,在等待的时候则是阻塞blocked的状态
如果调用wait或者join的方法,则变成waiting状态,
如果调用带时间参数的wait或者join,则变成time_waiting。