1. 程式人生 > >寫一個死鎖程序

寫一個死鎖程序

implement out over rri string dem new ble zed

/**

  • 死鎖
  • 產生死鎖的原因
  • 多個線程由於爭奪資源而產生的資源阻塞狀態
  • 同步的前提
  • 2個以上的線程 包含2
  • 多個線程使用同一個鎖
  • @author WangShuang
  • */
    public class Demo {
    public static void main(String[] args) {
    Test t = new Test(true);
    Thread rr=new Thread(t);
    rr.start();
    Test t1 = new Test(false);
    Thread rr1=new Thread(t1);
    rr1.start();
    }
    }
    class MyLock{
    public static Object lockA = new Object();

    public static Object lockB = new Object();
    }
    class Test implements Runnable{
    private boolean flag;
    public Test( boolean flag){this.flag=flag;
    }
    @Override
    br/>this.flag=flag;
    }
    @Override
    if(flag){
    synchronized (MyLock.lockA) {
    System.out.println("if lockA");
    synchronized (MyLock.lockB) {
    System.out.println("if lockB");
    }
    }
    }else{
    synchronized (MyLock.lockB) {
    System.out.println("else lockB");
    synchronized (MyLock.lockA) {
    System.out.println("else lockA");
    }
    }
    }
    }
    }

寫一個死鎖程序