• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

3.一个典型的死锁案例

开发技术 开发技术 2周前 (04-08) 3次浏览
public class DeadLock {

  public static void main(String[] args) {
    A a = new A();
    B b = new B();
    Dead dead1 = new Dead(true,a,b);
    Dead dead2 = new Dead(false,a,b);
    new Thread(dead1).start();
    new Thread(dead2).start();
  }

}

class A{

}
class B{

}
class Dead implements Runnable{
  boolean flag;
  A a;
  B b;

  public Dead(boolean flag, A a, B b) {
    this.flag = flag;
    this.a = a;
    this.b = b;
  }

  @Override
  public void run() {
    if(flag){
      synchronized (a){
        System.out.println("上面的我获取了a锁");
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        synchronized (b){
          System.out.println("上面的我获取了b锁");
        }
      }

    }else{
      synchronized (b){
        System.out.println("下面的我获取了b锁");
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        synchronized (a){
          System.out.println("下面的我获取了a锁");
        }
      }
    }
  }

  
}

  

如何解决这个死锁问题

public void run() {
    if(flag){
      synchronized (a){
        System.out.println("上面的我获取了a锁");
      }
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      synchronized (b){
        System.out.println("上面的我获取了b锁");
      }

    }else{
      synchronized (b){
        System.out.println("下面的我获取了b锁");
      }
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      synchronized (a){
        System.out.println("下面的我获取了a锁");
      }
    }
  }

  


程序员灯塔
转载请注明原文链接:3.一个典型的死锁案例
喜欢 (0)