死锁是指多个线程因竞争资源而造成的一种僵局
死锁产生的四个条件
- 互斥条件
- 不可剥夺条件
- 请求和保持条件
- 循环等待条件
死锁案例
DeadLock
public class DeadLock {
private ThirdService thirdService;
public DeadLock(ThirdService thirdService) {
this.thirdService = thirdService;
}
private final Object lock = new Object();
public void l1() {
synchronized (lock) {
System.out.println("l1================");
thirdService.s1();
}
}
public void l2() {
synchronized (lock) {
System.out.println("l2=================");
}
}
}
ThirdService
public class ThirdService {
private DeadLock deadLock;
public void setDeadLock(DeadLock deadLock) {
this.deadLock = deadLock;
}
private final Object thirdService = new Object();
public void s1() {
synchronized (thirdService) {
System.out.println("s1=======================");
}
}
public void s2() {
synchronized (thirdService) {
System.out.println("s2=======================");
deadLock.l2();
}
}
}
DeadLockTest
public class DeadLockTest {
public static void main(String[] args) {
ThirdService thirdService = new ThirdService();
DeadLock deadLock = new DeadLock(thirdService);
thirdService.setDeadLock(deadLock);
new Thread("t1") {
@Override
public void run() {
while (true) {
deadLock.l1();
}
}
}.start();
new Thread("t2"){
@Override
public void run() {
while (true) {
thirdService.s2();
}
}
}.start();
}
}
程序执行一会就会发生死锁
查看进程id
jps
查看死锁情况
jstack 7542