Java线程状态转换
前言:对于Java线程状态方面的知识点,笔者总感觉朦朦胧胧,趁着最近整理资料,将Java线程状态方面的知识点总结归纳,以便加深记忆。
1.Java线程状态值
在Thread类源码中通过枚举为线程定义了6种状态值。
1 public enum State { 2 /** 3 * Thread state for a thread which has not yet started. 4 */ 5 NEW, 6 7 /** 8 * Thread state for a runnable thread. A thread in the runnable 9 * state is executing in the Java virtual machine but it may 10 * be waiting for other resources from the operating system 11 * such as processor. 12 */ 13 RUNNABLE, 14 15 /** 16 * Thread state for a thread blocked waiting for a monitor lock. 17 * A thread in the blocked state is waiting for a monitor lock 18 * to enter a synchronized block/method or 19 * reenter a synchronized block/method after calling 20 * {@link Object#wait() Object.wait}. 21 */ 22 BLOCKED, 23 24 /** 25 * Thread state for a waiting thread. 26 * A thread is in the waiting state due to calling one of the 27 * following methods: 28 * <ul> 29 * <li>{@link Object#wait() Object.wait} with no timeout</li> 30 * <li>{@link #join() Thread.join} with no timeout</li> 31 * <li>{@link LockSupport#park() LockSupport.park}</li> 32 * </ul> 33 * 34 * <p>A thread in the waiting state is waiting for another thread to 35 * perform a particular action. 36 * 37 * For example, a thread that has called <tt>Object.wait()</tt> 38 * on an object is waiting for another thread to call 39 * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on 40 * that object. A thread that has called <tt>Thread.join()</tt> 41 * is waiting for a specified thread to terminate. 42 */ 43 WAITING, 44 45 /** 46 * Thread state for a waiting thread with a specified waiting time. 47 * A thread is in the timed waiting state due to calling one of 48 * the following methods with a specified positive waiting time: 49 * <ul> 50 * <li>{@link #sleep Thread.sleep}</li> 51 * <li>{@link Object#wait(long) Object.wait} with timeout</li> 52 * <li>{@link #join(long) Thread.join} with timeout</li> 53 * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> 54 * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li> 55 * </ul> 56 */ 57 TIMED_WAITING, 58 59 /** 60 * Thread state for a terminated thread. 61 * The thread has completed execution. 62 */ 63 TERMINATED; 64 }
NEW ---- 创建了线程对象但尚未调用start()方法时的状态。
RUNNABLE ---- 线程对象调用start()方法后,线程处于可运行状态,此时线程等待获取CPU执行权。
BLOCKED ---- 线程等待获取锁时的状态。
WAITING ---- 线程处于等待状态,处于该状态标识当前线程需要等待其他线程做出一些特定的操作唤醒自己。
TIME_WAITING ---- 超时等待状态,与WAITING不同,在等待指定的时间后会自行返回。
TERMINATED ---- 终止状态,表示当前线程已执行完毕。
2.线程状态转换
- 看图理解,下图对线程状态转换描述得非常清楚。
- 继续看图,将上下两张图片结合起来,理解就非常容易了。
- 只要充分理解上述两张图片,笔者相信就可以搞懂Java线程状态的转换关系了,如果你还有点懵懂,那么请看下图:
注:以上三张图片均来自于参考文章,对于最后一张图片有个小问题:t2.join()方法会释放锁。
总结
通过以上三张图片的描述,对Java线程状态转换的核心要点总结如下:
其实通过上面三张图片已经能很好的说明问题了,过多的总结反倒显得苍白无力。主要注意WAITING和BLOCKED状态:这两个状态下的线程都未运行,BLOCKED状态下,线程正等待锁;WAITING状态下,线程正等待被唤醒,唤醒后可能进入BLOCKED状态,继续等待锁,或者进入RUNNABLE状态,重新获取CPU时间片,继而等待获取锁。
参考:
https://my.oschina.net/mingdongcheng/blog/139263
https://github.com/c-rainstorm/blog/blob/master/java/谈谈Java线程状态转换.md
by Shawn Chen,2019.02.17,下午。