java线程状态解释

比较好的文章:https://blog.csdn.net/pange1991/article/details/53860651/

可以比较清楚看到6种状态

下面对主要3中状态进行解释

1:BLOCKED

/**
 * 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.
 */

如上注释所言,这是一个运行中线程,因为等待一个别的资源进入的状态。一般就是因为等待锁变为这个状态。例如使用synchronized关键字造成的锁等待。(jvisualvm中的监视(中文翻译)/monitor状态)
通过jstack发现是 BLOCKED (on object monitor)

2.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(100);(jstack显示的TIMED_WAITTING状态,jvisumlvm中的休眠/sleeping状态)

3.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
  • *
  • {@link #join() Thread.join} with no timeout
  • *
  • {@link LockSupport#park() 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.

线程进入等待状态,进入的方式如上注释3中情况,因为ReentrantLock,CountDownLoatch使用LockSupport#park()进入等待状态(jvisualvm中的驻留(中文)/Park状态,如果调用sleep,wait()方法在jvisualvm分别是sleeping,wait状态,在jstack是WAITTING(sleeping/wait/park)),会通过后面的括号分割开。

可以看到因锁阻塞和主动调用sleep,park,await等方法,线程进入的状态是不同,JVM线程状态前者是BLOCKED,后者是WAITTING。
这里有个在JVM中WAITTING与BLOCKED状态下不同的解释 https://javaconceptoftheday.com/difference-between-blocked-vs-waiting-states-in-java/
主要的不同是WAITTING可以被中断。

java线程与os线程状态对应图(来源:https://my.oschina.net/goldenshaw/blog/802620)
java线程状态解释_第1张图片

还有一个超时等待状态,凡是可以设置等待一个时间端的,都是进入这个状态,时间到了,自动唤醒。

PS:
1.多次调用start会报线程状态不对的错误

2.java synchronized等待锁时时BLOCKED状态,Reentractlock是调用Unsafe.park()方法挂起,所以是WAITTING(park)状态

3.java线程WAITTING、TIMED_WAITTING、BLOCKED对应os的waitting状态

你可能感兴趣的:(java)