一、命令行工具jstack
用于查看线程状态
例子
public class ThreadState {
public static void main(String[] args) {
new Thread(new TimeWaiting(), "TimeWaitingThread").start();
new Thread(new Waiting(), "WaitingThread").start();
// 使用两个Blocked线程,一个获取锁成功,另一个被阻塞
new Thread(new Blocked(), "BlockedThread-1").start();
new Thread(new Blocked(), "BlockedThread-2").start();
}
// 该线程不断地进行睡眠
static class TimeWaiting implements Runnable {
@Override
public void run() {
while (true) {
try {
TimeUnit.SECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 该线程在Waiting.class实例上等待
static class Waiting implements Runnable {
@Override
public void run() {
while (true) {
synchronized (Waiting.class) {
try {
Waiting.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
// 该线程在Blocked.class实例上加锁后,不会释放该锁
static class Blocked implements Runnable {
public void run() {
synchronized (Blocked.class) {
while (true) {
try {
TimeUnit.SECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
启动以上程序后,控制台上输入jps 查看进程
$ jps
7012 Main
32037 Jps
26870 Main
31862 Launcher
31863 ThreadState
29629 KotlinCompileDaemon
查看 ThreadState 的状态 : jstack 进程id
jstack 31863
//...省略
//BlockedThread-2 阻塞状态: BLOCKED
"BlockedThread-2" #13 prio=5 os_prio=0 tid=0x00007f0dd8214800 nid=0x7c98 waiting for monitor entry [0x00007f0dc1600000]
java.lang.Thread.State: BLOCKED (on object monitor)
at concurrency.ThreadState$Blocked.run(ThreadState.java:54)
- waiting to lock <0x00000000d93089b0> (a java.lang.Class for concurrency.ThreadState$Blocked)
at java.lang.Thread.run(Thread.java:748)
// BlockedThread-1 获取了锁,执行sleep()方法,进入超时等待状态: TIMED_WAITING
"BlockedThread-1" #12 prio=5 os_prio=0 tid=0x00007f0dd8213000 nid=0x7c97 waiting on condition [0x00007f0dc1701000]
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at concurrency.ThreadState$Blocked.run(ThreadState.java:54)
- locked <0x00000000d93089b0> (a java.lang.Class for concurrency.ThreadState$Blocked)
at java.lang.Thread.run(Thread.java:748)
//WaitingThread 等待状态: WAITING
"WaitingThread" #11 prio=5 os_prio=0 tid=0x00007f0dd8211000 nid=0x7c96 in Object.wait() [0x00007f0dc1802000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00000000d9308dc8> (a java.lang.Class for concurrency.ThreadState$Waiting)
at java.lang.Object.wait(Object.java:502)
at concurrency.ThreadState$Waiting.run(ThreadState.java:39)
- locked <0x00000000d9308dc8> (a java.lang.Class for concurrency.ThreadState$Waiting)
at java.lang.Thread.run(Thread.java:748)
// TimeWaitingThread 超时等待状态:TIMED_WAITING
"TimeWaitingThread" #10 prio=5 os_prio=0 tid=0x00007f0dd8210000 nid=0x7c95 waiting on condition [0x00007f0dc1903000]
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at concurrency.ThreadState$TimeWaiting.run(ThreadState.java:24)
at java.lang.Thread.run(Thread.java:748)
//省略...