只有以下这四个条件都发生时才会出现死锁:
1. 互斥,共享资源 X 和 Y 只能被一个线程占用;
2. 占有且等待,线程 T1 已经取得共享资源 X,在等待共享资源 Y 的时候,不释放共享资源 X;
3. 不可抢占,其他线程不能强行抢占线程 T1 占有的资源;
4. 循环等待,线程 T1 等待线程 T2 占有的资源,线程 T2 等待线程 T1 占有的资源,就是循环等
待。
如何避免死锁:
1. 对于“占用且等待”这个条件,我们可以一次性申请所有的资源,这样就不存在等待了。
2. 对于“不可抢占”这个条件,占用部分资源的线程进一步申请其他资源时,如果申请不到,可 以主动释放它占有的资源,这样不可抢占这个条件就破坏掉了。
3. 对于“循环等待”这个条件,可以靠按序申请资源来预防。所谓按序申请,是指资源是有线性 顺序的,申请的时候可以先申请资源序号小的,再申请资源序号大的,这样线性化后自然就不 存在循环了。
示例: 用户A转账给用户B,用户B转账给用户A
public class Account {
private Integer balance = 200;
private void transfer(Account target, int amount){
synchronized (this){
synchronized (target){
if(this.balance >= amount){
this.balance -= amount;
target.balance += amount;
}
}
}
}
public static void main(String[] args){
for(int i = 0 ; i < 100000 ; i++ ) {
Account account1 = new Account();
Account account2 = new Account();
Account account3 = new Account();
Account account4 = new Account();
Thread th1 = new Thread(() -> {
account1.transfer(account2, 100);
});
Thread th2 = new Thread(() -> {
account2.transfer(account1, 100);
});
th1.start();
th2.start();
try {
th1.join();
th2.join();
} catch (Exception e) {
System.out.println(e);
}
System.out.println(i);
}
}
}
重复试验直到有死锁现象出现,运用jconsole工具查看死锁
本地进程 -> 连接
线程 -> 检查死锁 :两个线程分别占有对方所需要的锁,形成死锁