JDK api官方文档中给出的Thread.State的说明如下:
-
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.
A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states.
-
-
Since:
- 1.5
下面根据个人的了解,结合下图,对各个状态进行说明
1)NEW
当新建一个线程Thread对象的时候,并且没有调用start()方法之前,线程处于NEW状态
2)RUNNABLE
线程处于就绪或者是运行状态,也就是获取了CPU资源在跑着没有阻塞
3)BLOCKED
当线程没有获取到锁对象,等待获取锁对象的时候,处于阻塞状态
4)WAITING
当线程等待另一个特定的线程处理完之后,才继续往下执行,这种情况下也是阻塞状态。 该情况发生在调用 Thread.join() 方法。
例如:
public static void main(String args[]) throws InterruptedException{
System.out.println("进入主线程" + Thread.currentThread().getName());
Thread thread1 = new Thread(new ThreadRunnable());
thread1.start();
thread1.join();
System.out.println("退出主线程" + Thread.currentThread().getName());
}
在这个例子中,主线程执行thread1.join() 代码之后,会一直处于阻塞状态,直到 thread1线程执行完之后,阻塞状态解除,继续往下执行!!
5)TIMED_WAITING
线程让出CPU资源给其它线程,等待指定的时间之后,才重新进入线程队列中,等待获取CPU资源,这种情况下也是阻塞状态。该情况发生在调用Thread.sleep()方法