🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 多线程死锁案例以及查看方法 我们先定义一个类调用`DeadLock`和`OtherService`。 ```java public class DeadLockTest { public static void main(String[] args) { DeadLock deadLock = new DeadLock(); OtherService otherService = new OtherService(); deadLock.setOtherService(otherService); otherService.setDeadLock(deadLock); new Thread(() -> { while (true) { deadLock.m1(); } }, "T1").start(); new Thread(() -> { while (true) { otherService.s2(); } }, "T2").start(); } } ``` ```java public class DeadLock { private OtherService otherService; public void setOtherService(OtherService otherService) { this.otherService = otherService; } // DeadLock的实例的锁-资源A private final Object LOCK = new Object(); public void m1() { synchronized (LOCK) { System.out.println("********m1********"); otherService.s1(); } } public void m2() { synchronized (LOCK) { System.out.println("********m2********"); } } } ``` ```java public class OtherService { private DeadLock deadLock; public void setDeadLock(DeadLock deadLock) { this.deadLock = deadLock; } // OtherService的实例的锁-资源B private final Object LOCK = new Object(); public void s1() { synchronized (LOCK) { System.out.println("========s1========"); } } public void s2() { synchronized (LOCK) { System.out.println("========s2========"); deadLock.m2(); } } } ``` 可以看到: 线程一调用`DeadLock`的`m1`方法,`m1`使用了`DeadLock`的`LOCK`锁,`m1`调用了`OtherService`的`s1`,`s1`使用了`DeadLock`的`LOCK`锁,线程二调用`OtherService`的`s2`,而`s2`调用了`DeadLock`的`m2`,而m2使用的DeadLock的LOCK被m1抢占着,所以就形成了死锁。 接下来使用`jps`和`jstack`命令来看一下: ![](https://img.kancloud.cn/55/c8/55c898c4479b17e3a06645e1ac2f88ac_960x430.gif)