当前位置: 代码迷 >> J2SE >> 线程 死锁解决办法
  详细解决方案

线程 死锁解决办法

热度:469   发布时间:2016-04-23 19:48:33.0
线程 死锁
public class  死锁Test  implements Runnable
{
  public static Object S1 = new Object();
  public static Object S2 = new Object();
  public void run() {
      if(Thread.currentThread().getName().equals("PH1")) {
      synchronized(S1) {
    System.out.println("线程1锁定S1");
try {
 Thread.sleep(1000);
}catch(Exception ex) {
}
synchronized(S2){
  System.out.println("线程1锁定S2");
}
  }
  }else{
      synchronized(S2) {
    System.out.println("线程2锁定S2");
    synchronized(S1) {
    System.out.println("线程2锁定S2");
}
  }
  }
  }
  
  public static void main(String[] args) {
       Thread t1 = new Thread(new 死锁Test(),"PH1");
   Thread t2 = new  Thread(new 死锁Test(),"PH2");
   t1.start();
   t2.start();
  }
}

为什么这个程序不能 死锁        怎么稍微修改一下就出现死锁           求大牛指导  谢谢
------解决思路----------------------
public class  LockTest  implements Runnable
{
    public LockTest(Object S1,Object S2){
        this.S1 = S1;this.S2 = S2;
    }
    public  Object S1;
    public  Object S2;
    public void run() {
        if(Thread.currentThread().getName().equals("PH1")) {
            synchronized(S1) {
                System.out.println("线程1锁定S1");
                try {
                    Thread.sleep(1000);
                }catch(Exception ex) {
                }
                synchronized(S2){
                    System.out.println("线程1锁定S2");
                }
            }
        }else{
            synchronized(S2) {
                System.out.println("线程2锁定S2");
                synchronized(S1) {
                    System.out.println("线程2锁定S2");
                }
            }
        }
    }

    public static void main(String[] args) {
        Object S1 = new Object();Object S2 = new Object();
        Thread t1 = new Thread(new LockTest(S1,S2),"PH1");
        Thread t2 = new  Thread(new LockTest(S1,S2),"PH2");
        t1.start();
        t2.start();
    }
}

------解决思路----------------------
public class  死锁Test  implements Runnable
{
  public static Object S1 = new Object();
  public static Object S2 = new Object();
  public void run() {
      if(Thread.currentThread().getName().equals("PH1")) {
      synchronized(S1) {
    System.out.println("线程1锁定S1");
try {
 Thread.sleep(1000);
}catch(Exception ex) {
}
synchronized(S2){
  System.out.println("线程1锁定S2");
}
  }
  }else{
      synchronized(S2) {
    System.out.println("线程2锁定S2");
    synchronized(S1) {
    System.out.println("线程2锁定S2");
}
  }
  }
  }
  
  public static void main(String[] args) {
       死锁Test st=new 死锁Test();
       Thread t1 = new Thread(st,"PH1");
   Thread t2 = new  Thread(st,"PH2");
   t1.start();
   t2.start();
  }
}
  相关解决方案