什么是死锁
死锁是指两个或者两个以上的线程在执行过程中,因为争夺资源而造成的一种相互等待的现象,若无外力干涉,那它们都将无法推进下去。
代码举例
public class DeadLockDemo {
public static void main(String[] args) {
String la = "lock-a";
String lb = "lock-b";
new Thread(new HoldLock(la, lb), "T-A").start();
new Thread(new HoldLock(lb, la), "T-B").start();
}
}
class HoldLock implements Runnable {
private String lockA;
private String lockB;
public HoldLock(String lockA, String lockB) {
this.lockA = lockA;
this.lockB = lockB;
}
@Override
public void run() {
synchronized (lockA) {
System.out.println(Thread.currentThread().getName() + " >> 持有锁: " + lockA + " 尝试获取: " + lockB);
try {
Thread.sleep(2000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB) {
System.out.println(Thread.currentThread().getName() + " -- 持有锁: " + lockB + " 尝试获取: " + lockA);
}
}
}
}
死锁排查
获取怀疑产生死锁的进程id
使用jps命令获取
使用ps命令获取
打印死锁堆栈信息
使用jdk自带的jstack命令获取堆栈信息
jstack 6911