Java线程状态转换

时间:2023-12-28 20:45:32

前言:对于Java线程状态方面的知识点,笔者总感觉朦朦胧胧,趁着最近整理资料,将Java线程状态方面的知识点总结归纳,以便加深记忆。

1.Java线程状态值

在Thread类源码中通过枚举为线程定义了6种状态值。

 public enum State {
/**
* Thread state for a thread which has not yet started.
*/
NEW, /**
* 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.
*/
RUNNABLE, /**
* 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}.
*/
BLOCKED, /**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link Object#wait() Object.wait} with no timeout</li>
* <li>{@link #join() Thread.join} with no timeout</li>
* <li>{@link LockSupport#park() LockSupport.park}</li>
* </ul>
*
* <p>A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called <tt>Object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
* that object. A thread that has called <tt>Thread.join()</tt>
* is waiting for a specified thread to terminate.
*/
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:
* <ul>
* <li>{@link #sleep Thread.sleep}</li>
* <li>{@link Object#wait(long) Object.wait} with timeout</li>
* <li>{@link #join(long) Thread.join} with timeout</li>
* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
* </ul>
*/
TIMED_WAITING, /**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
TERMINATED;
}
NEW          ---- 创建了线程对象但尚未调用start()方法时的状态。
RUNNABLE ---- 线程对象调用start()方法后,线程处于可运行状态,此时线程等待获取CPU执行权。
BLOCKED ---- 线程等待获取锁时的状态。
WAITING ---- 线程处于等待状态,处于该状态标识当前线程需要等待其他线程做出一些特定的操作唤醒自己。
TIME_WAITING ---- 超时等待状态,与WAITING不同,在等待指定的时间后会自行返回。
TERMINATED ---- 终止状态,表示当前线程已执行完毕。

2.线程状态转换

  • 看图理解,下图对线程状态转换描述得非常清楚。

Java线程状态转换

  • 继续看图,将上下两张图片结合起来,理解就非常容易了。

Java线程状态转换

  • 只要充分理解上述两张图片,笔者相信就可以搞懂Java线程状态的转换关系了,如果你还有点懵懂,那么请看下图:

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,下午。