死锁

class Tacket implements Runnable{
 private int tacket=100;
 private Object obj1=new Object();
 private Object obj2=new Object();
 boolean flag;
 Tacket(boolean flag){
  this.flag=flag;
 }
 public void run(){
  if(flag){
   while(true){
    synchronized(obj1){
     synchronized(obj2){
      if(tacket>0){
       try{Thread.sleep(2);}catch(InterruptedException e){};
       System.out.println(Thread.currentThread().getName()+"...obj..."+(--tacket));
      }
     }
    }
   }
  }else{
   while(true){
    synchronized(obj2){
     synchronized(obj1){
      if(tacket>0){
       try{Thread.sleep(2);}catch(InterruptedException e){};
       System.out.println(Thread.currentThread().getName()+"...sale..."+(--tacket));
      }
     }
    }

   }
  } 
 }
 //public synchronized void sale(){
 // if(tacket>0){
 //  try{Thread.sleep(2);}catch(InterruptedException e){};
 //  System.out.println(Thread.currentThread().getName()+"...sale..."+(--tacket));
 // }
 //}
}
public class text35{
 public static void main(String[] args){
  Tacket t1=new Tacket(true);
  Tacket t2=new Tacket(false);
  Thread T1=new Thread(t1);
  Thread T2=new Thread(t2);
  T1.start();
  T2.start();
 }
}

原文地址:https://www.cnblogs.com/daoxiang1992/p/5701488.html