10.1 是什么

死锁是指两个或两个以上的进程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力干涉那它们都将无法推进下去,如果系统资源充足,进程的资源请求都能够得到满足,死锁出现的可能性就很低,否则就会因争夺有限的资源而陷入死锁。
image.png
产生死锁主要原因:

  • 系统资源不足
  • 进程运行推进的顺序不合适
  • 资源分配不当 ```java package s02.e10;

import java.util.concurrent.TimeUnit;

class HoldLockThread implements Runnable { private String lockA; private String lockB;

  1. public HoldLockThread(String lockA, String lockB) {
  2. this.lockA = lockA;
  3. this.lockB = lockB;
  4. }
  5. @Override
  6. public void run() {
  7. synchronized (lockA) {
  8. System.out.println(Thread.currentThread().getName() + "\t 自己持有:" + lockA + "\t尝试获取:" + lockB);
  9. try {
  10. TimeUnit.SECONDS.sleep(2);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. synchronized (lockB) {
  15. System.out.println(Thread.currentThread().getName() + "\t 自己持有:" + lockB + "\t尝试获取:" + lockA);
  16. }
  17. }
  18. }

}

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(); } }

  1. ![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)
  2. <a name="dclGm"></a>
  3. # 10.2 如何排查死锁
  4. 1. jps 命令定位进程号
  5. ```bash
  6. jps -l

image.png

  1. jstack 找到死锁查看
    1. jstack [进程号]
    image.png