Java 线程(一):线程状态

本文详细解析了Java中线程的六种状态:NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING和TERMINATED,以及Blocked和Waiting状态的区别。通过JavaVisualVM工具和ThreadsInspector插件,开发者可以有效监控和管理线程状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

监控工具

Java VisualVM 是可视化的查看JVM运行信息的工具,位于 $JAVA_HOME/bin/jvisualvm

官方文档 https://docs.oracle.com/javase/8/docs/technotes/guides/visualvm/

在菜单工具-插件,安装 Threads Inspector 插件可以查看线程运行状态。

 

线程状态

Thead的内部枚举类定义了JVM层面的6种线程状态。

  • NEW

Thread state for a thread which has not yet started.

未启动的线程状态。

  • 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.

线程在JVM 中可运行,执行权交给 OS。

  • 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 Object.wait.

线程等在获取 monitor lock,两类情况:一个线程等待 monitor lock 来进入同步代码块或同步方法;一个线程执行到同步代码块或者方法中的 Object.wait() 方法后处于 WAITING 状态,当其他线程调用 Object.notifyAll() 后再次尝试进入(reenter)同步代码块或方法时等待 monitor lock。

  • WAITING

Thread state for a waiting thread. A thread is in the waiting state due to calling one of the following methods:

    • Object.wait with no timeout
    • Thread.join with no timeout
    • LockSupport.park

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() is waiting for a specified thread to terminate.

JVM层面的等待或者阻塞。

  • 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:
    • Thread.sleep
    • Object.wait with timeout
    • Thread.join with timeout
    • LockSupport.parkNanos
    • LockSupport.parkUntil
  • TERMINATED

Thread state for a terminated thread. The thread has completed execution.

线程执行结束或者异常结束。

 

Blocked 和 Waiting 状态区别

可以简单理解线程为了对共享资源(同步代码块或者同步方法)的独占。

  1. 获取不到 monitor lock 时进入 block set 处于 Blocked 状态。
  2. 进入同步代码块后发现缺少某种资源,调用 Object.wait() 先释放共享资源(同步代码块或者同步方法)线程进入 wait set 处于 Waiting 状态,等待调用 Object.notifyAll() 呼唤自己出队,出队后重新尝试(reenter)获取共享资源(同步代码块或者同步方法)。

 

线程生命周期

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值