死锁
多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或多个线程都在相互等待对方释放资源,僵持着,都停止执行的情形,某一个同步块同时拥有"两个以上对象的锁"时,就可能发生"死锁"的问题。
package com.example.demo.testthread;
public class TestDiedLock implements Runnable {
private String weapon1;
private String weapon2;
public TestDiedLock(String weapon1, String weapon2) {
this.weapon1 = weapon1;
this.weapon2 = weapon2;
}
public void getWeapon1() {
System.out.println(Thread.currentThread().getName() + "获得了武器:" + this.weapon1);
}
public void getWeapon2() {
System.out.println(Thread.currentThread().getName() + "获得了武器:" + this.weapon2);
}
@Override
public void run() {
if (Thread.currentThread().getName().equals("金毛狮王-谢逊")) {
synchronized (this.weapon1) {//获得了第一个锁
getWeapon1();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this.weapon2) {//不释放,并想获得另一把锁
getWeapon2();
}
}
} else {
synchronized (this.weapon2) {
getWeapon2();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this.weapon1) {
getWeapon1();
}
}
}
}
public static void main(String[] args) {
TestDiedLock lock = new TestDiedLock("屠龙刀", "倚天剑");
Thread t1 = new Thread(lock, "金毛狮王-谢逊");
Thread t2 = new Thread(lock, "灭绝师太");
t1.start();
t2.start();
}
}
死锁避免方法
产生死锁的四个不要条件
- 互斥条件:一个资源每次只能被一个进程使用
- 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
只需要破坏其中任意一个或多个条件,就可以避免死锁发生