1.死锁的产生
在请求资源的时候,一个线程运行锁到了一个资源(a),要拿下一个资源(b),在此同时又一个线程已经拿到资源(b),需要拿下一个资源(a)从而形成了死锁
package com.zzg.thread.test;
public class JavaTest {
public static void main(String[] args) {
Object a = new Object();
Object b = new Object();
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "获取a");
synchronized (a) {
System.out.println(Thread.currentThread().getName() + "要拿到b");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (b) {
System.out.println(Thread.currentThread().getName() + "获取b");
}
}
}).start();
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "获取b");
synchronized (b) {
System.out.println(Thread.currentThread().getName() + "要拿到a");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (a) {
System.out.println(Thread.currentThread().getName() + "获取a");
}
}
}).start();
}
}
2死锁的关系
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4wRZGzxX-1646740753878)(C:\Users\张中贵\Desktop\2022-03-08_194842.png)]
3.死锁的解决方案
占有且等待:每个请求者一次性请所有所需要的资源,如果无法申请所有的资源那个对资源进行占有,那就进行等待
破坏不可抢占:当某个资源拿到申请时,去拿下一个资源,如果不能拿到,那就放弃之前占有所有资源
循环等待:对所需要的资源进行排序,让线程申请时先申请小的在申请大的
不能拿到,那就放弃之前占有所有资源
循环等待:对所需要的资源进行排序,让线程申请时先申请小的在申请大的