10.1 是什么
死锁是指两个或两个以上的进程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力干涉那它们都将无法推进下去,如果系统资源充足,进程的资源请求都能够得到满足,死锁出现的可能性就很低,否则就会因争夺有限的资源而陷入死锁。
产生死锁主要原因:
- 系统资源不足
- 进程运行推进的顺序不合适
- 资源分配不当 ```java package s02.e10;
import java.util.concurrent.TimeUnit;
class HoldLockThread implements Runnable { private String lockA; private String lockB;
public HoldLockThread(String lockA, String lockB) {
this.lockA = lockA;
this.lockB = lockB;
}
@Override
public void run() {
synchronized (lockA) {
System.out.println(Thread.currentThread().getName() + "\t 自己持有:" + lockA + "\t尝试获取:" + lockB);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB) {
System.out.println(Thread.currentThread().getName() + "\t 自己持有:" + lockB + "\t尝试获取:" + lockA);
}
}
}
}
public class DeadLockDemo { public static void main(String[] args) { String lockA = “1ockA”; String lockB = “lockB”; new Thread(new HoldLockThread(lockA, lockB), “ThreadAAA”).start(); new Thread(new HoldLockThread(lockB, lockA), “ThreadBBB”).start(); } }
![image.png](https://cdn.nlark.com/yuque/0/2022/png/390086/1645718550375-bdfe9c72-3280-4969-be5b-788522933723.png#clientId=u43a59502-fd26-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=47&id=u5d6f1613&margin=%5Bobject%20Object%5D&name=image.png&originHeight=47&originWidth=350&originalType=binary&ratio=1&rotation=0&showTitle=false&size=3808&status=done&style=none&taskId=u7978cf16-5651-4270-a2e8-ea5d9aad420&title=&width=350)
<a name="dclGm"></a>
# 10.2 如何排查死锁
1. jps 命令定位进程号
```bash
jps -l
- jstack 找到死锁查看
jstack [进程号]