使用JDK自带命令分析死锁问题

首先写一段死锁代码跑起来

package com.demo;
public class DeadLock {
private Object lock1 = new Object();
private Object lock2 = new Object();
public static void main(String[] args) {
final DeadLock dLock = new DeadLock();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
dLock.test1(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
dLock.test2(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
private void test1(int count) throws InterruptedException {
synchronized (lock1) {
synchronized (lock2) {
System.out.println(“test1 done” + count);
Thread.sleep((long) (Math.random() * 1000));
}
}
}
private void test2(int count) throws InterruptedException {
synchronized (lock2) {
synchronized (lock1) {
System.out.println(“test2 done” + count);
Thread.sleep((long) (Math.random() * 1000));
}
}
}
}

运行结果如下: 使用jps命令查看当前死锁进程号 再用jstack命令加上一步查到的进程号,来进一步查看该进程的堆栈信息,关注最下面的部分,已经自动检测到死锁相关信息,排查起来很方便: