多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,这导致两个或多个线程都在等待对方释放资源,形成僵持停止执行。
某一个同步块同时拥有两个以上对象的锁时,就可能会发生死锁
HR:说说死锁吧
我:你先给我发offer
双方都抱着对方需要的资源不肯让步,形成僵持,这种现象就是死锁
//死锁 多个线程互相抱着对方需要的资源,形成僵持
public class DeadLock {
public static void main(String[] args) {
Interview HR = new Interview(0, "HR");
Interview Me = new Interview(1, "我");
HR.start();
Me.start();
}
}
//Offer
class Offer{
}
//Answer
class Answer{
}
//面试
class Interview extends Thread{
//需要的资源只有一份 static
static Offer offer = new Offer();
static Answer answer = new Answer();
int choice; //选择
String name; //身份
//构造方法
Interview(int choice, String name){
this.choice = choice;
this.name = name;
}
//面试过程
@Override
public void run() {
try {
interview();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//面试过程
private void interview() throws InterruptedException {
if(choice == 0){
synchronized (offer){ //获得offer的锁
System.out.println(this.name + "获得offer的锁");
Thread.sleep(1000);
synchronized (answer){
System.out.println(this.name + "获得answer的锁");
}
}
}else {
synchronized (answer){ //获得offer的锁
System.out.println(this.name + "获得answer的锁");
Thread.sleep(1000);
synchronized (offer){
System.out.println(this.name + "获得offer的锁");
}
}
}
}
}
HR抱着offer,我抱着answer,谁都不愿意给谁,形成僵持
此时只要让HR和我不同时抱着一把锁就可以了
//面试过程
private void interview() throws InterruptedException {
if(choice == 0){
synchronized (offer){ //获得offer的锁
System.out.println(this.name + "获得offer的锁");
Thread.sleep(1000);
}
synchronized (answer){
System.out.println(this.name + "获得answer的锁");
}
}else {
synchronized (answer){ //获得offer的锁
System.out.println(this.name + "获得answer的锁");
Thread.sleep(1000);
}
synchronized (offer){
System.out.println(this.name + "获得offer的锁");
}
}
}
我做出了让步,给了他answer的锁,于是我获得了offer的锁
死锁避免方法
产生死锁的四个必要条件,不满足其中一个或多个即可避免死锁发生
1.互斥条件:一个资源每次只能被一个进程使用
2.请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
3.不剥夺条件:进程已获得的资源,在未使用完之前不能强行剥夺
4.循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系