JVM优化之使用Jstack命令查找JVM死锁
示例代码
public class DeadLockDemo {
private static Object lock1 = new Object();
private static Object lock2 = new Object();
public static void main(String[] args) {
new Thread(() -> {
synchronized (lock1) {
try {
System.out.println("thread1 begin");
Thread.sleep(5000);
} catch (InterruptedException e) {
}
synchronized (lock2) {
System.out.println("thread1 end");
}
}
}).start();
new Thread(() -> {
synchronized (lock2) {
try {
System.out.println("thread2 begin");
Thread.sleep(5000);
} catch (InterruptedException e) {
}
synchronized (lock1) {
System.out.println("thread2 end");
}
}
}).start();
}
}
使用下面的命令输出线程信息
jstack <pid>
“Thread-1” 线程名
prio=5 优先级=5
tid=0x0000028ae51d6000 线程id
nid=0x8778 线程对应的本地线程标识nid
java.lang.Thread.State: BLOCKED 线程状态
通过输出结果,可以看到有一个线程死锁,Thread-0和Thread-1在进行资源的竞争,同时也输出了资源竞争代码所在行。