多线程死锁案例以及查看方法
作者:互联网
多线程死锁案例以及查看方法
我们先定义一个类调用DeadLock
和OtherService
。
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();
}
}
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********");
}
}
}
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
命令来看一下:
标签:DeadLock,LOCK,deadLock,案例,死锁,OtherService,多线程,public,otherService 来源: https://www.cnblogs.com/stormsquirrel/p/13622121.html