更多 Java 并發(fā)編程方面的文章栗竖,請參見文集《Java 并發(fā)編程》
基本使用
首先使用 jps -l
查找當(dāng)前所有的 Java 進程寸爆。
隨后使用 jstack -pid
查看特定 Java 進行的 Thread Dump岳颇,如果需要將結(jié)果導(dǎo)出到文件,可以使用 jstack -pid > dump.out
饲化。
Thread Dump 包含的內(nèi)容
- thread name:線程名
- thread id:線程 ID
-
java.lang.Thread.State:線程狀態(tài)蝌数,包括:
- NEW
- RUNNABLE
-
BLOCKED:Waiting for a monitor lock,等待進入
synchronized
代碼塊 -
WAITING:包括三種情況:
- 當(dāng)前線程調(diào)用了不帶參數(shù)的
obj.wait()
- 其他線程調(diào)用了不帶參數(shù)的
t2.join()
- 調(diào)用了
LockSupport.park()
- 當(dāng)前線程調(diào)用了不帶參數(shù)的
-
TIMED_WAITING:包括三種情況:
- 當(dāng)前線程調(diào)用了帶參數(shù)的
obj.wait(1000)
- 其他線程調(diào)用了帶參數(shù)的
t2.join(1000)
- 當(dāng)前線程調(diào)用了
Thread.sleep(1000)
- 調(diào)用了
LockSupport.parkNanos()
- 調(diào)用了
LockSupport.parkUntil()
- 當(dāng)前線程調(diào)用了帶參數(shù)的
- TERMINATED
- Stack Trace:線程執(zhí)行路徑
- 鎖定了哪些資源贷祈,在等待哪些資源
示例
執(zhí)行一段導(dǎo)致死鎖的 Java 代碼趋急,參見 Java 死鎖 DeadLock,隨后導(dǎo)出其 TheadDump 文件势誊。
其中的部分內(nèi)容如下:
"Thread-1" #12 prio=5 os_prio=0 tid=0x000000001d5f7000 nid=0x2c48 waiting for monitor entry [0x000000001ea6f000]
java.lang.Thread.State: BLOCKED (on object monitor)
at DeadLockThread.run(DeadLockTesting.java:57)
- waiting to lock <0x000000076b2ba340> (a java.lang.Object)
- locked <0x000000076b2ba350> (a java.lang.Object)
"Thread-0" #11 prio=5 os_prio=0 tid=0x000000001d5e4000 nid=0x2f7c waiting for monitor entry [0x000000001e7cf000]
java.lang.Thread.State: BLOCKED (on object monitor)
at DeadLockThread.run(DeadLockTesting.java:57)
- waiting to lock <0x000000076b2ba350> (a java.lang.Object)
- locked <0x000000076b2ba340> (a java.lang.Object)
Found one Java-level deadlock:
=============================
"Thread-1":
waiting to lock monitor 0x000000001c13c338 (object 0x000000076b2ba340, a java.lang.Object),
which is held by "Thread-0"
"Thread-0":
waiting to lock monitor 0x000000001c13c1d8 (object 0x000000076b2ba350, a java.lang.Object),
which is held by "Thread-1"
Java stack information for the threads listed above:
===================================================
"Thread-1":
at DeadLockThread.run(DeadLockTesting.java:57)
- waiting to lock <0x000000076b2ba340> (a java.lang.Object)
- locked <0x000000076b2ba350> (a java.lang.Object)
"Thread-0":
at DeadLockThread.run(DeadLockTesting.java:57)
- waiting to lock <0x000000076b2ba350> (a java.lang.Object)
- locked <0x000000076b2ba340> (a java.lang.Object)
Found 1 deadlock.
可以看出:
- Thread-1 鎖定了0x000000076b2ba350呜达, 在等待 monitor 0x000000076b2ba340
- Thread-0 鎖定了0x000000076b2ba340,在等待 monitor 0x000000076b2ba350
- 因此發(fā)現(xiàn)了一個死鎖