2019年5月

读懂 thread heap

  1. 第一行是线程基本信息, 分别是 线程名字, 是否是Daemon线程(如果不是就不显示), 线程优先级, 线程id, OS native 线程id, 当前运行的状态[当前在那个对象对象].

  2. 当前线程的状态

  3. 下面就是当前线程的Stack;

    "DefaultThreadPool-89" daemon prio=10 tid=0x00007f3974036000 nid=0xb4a waiting on condition [0x00007f393e7e4000]
    java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for <0x00000007ac99baf8> (a com.ebay.raptor.orchestration.impl.FutureCallableTask)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
    at java.util.concurrent.FutureTask.awaitDone(FutureTask.java:425)
    at java.util.concurrent.FutureTask.get(FutureTask.java:187)

  4. Java 线程有6种状态: New, Runnable, Blocked, Waiting, Timed Waiting, Terminated. 对应到 thread dump 里面: 到现在做的 thread dump 里面没有看到状态是 New的. 也没有看到 Terminated 的. 其它都看到过:
    java.lang.Thread.State: RUNNABLE

java.lang.Thread.State: BLOCKED (on object monitor)

java.lang.Thread.State: TIMED_WAITING (sleeping)
java.lang.Thread.State: TIMED_WAITING (parking)
java.lang.Thread.State: TIMED_WAITING (on object monitor)

java.lang.Thread.State: WAITING (parking)
java.lang.Thread.State: WAITING (on object monitor)

  1. JVM 6种线程定义:

    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.

  2. 什么情况下会进入 blocked 状态?
    根据 Thread.State 类的描述: 1. 当一个线程在准备进入Synchronized的块/方法的时候, 2. 或者该线程之前已经进入synchronized 块/方法, 之后又call 了 Object.wait, 这个时候, 该线程进入 Waiting状态 或者 timed_waiting 状态, 之后又被 notify 或notifyAll 唤醒, 等待重新进入Synchronized同步块/方法, 这时候又进入blocked 状态.

  3. 什么情况会进入 waiting 状态?
    等待某种事件发生.
    Object.wait with no timeout -> 等待notify 或 notifyAll
    Thread.join with no timeout -> 等待特定线程终止
    LockSupport.park -> 等待 unpark

  4. 什么情况会进入 timed_waiting 状态?
    虽然等待某种特殊事件发生, 不过最多只等待特定时间
    Thread.sleep
    Object.wait with timeout
    Thread.join with timeout
    LockSupport.parkNanos
    LockSupport.parkUntil