java中同步嵌套引起的死锁事例代码

/*
 目的:自己写一个由于同步嵌套引起的死锁!
 思路:多个线程在执行时,某一时刻,0-Thread绑定了LockA锁,1-Thread绑定了LockB锁!
 当0-Thread要去绑定LockB锁时 和 1-Thread要去绑定LockA锁时都不能绑定,此时两个线程不能继续进行!
*/
class Ticket implements Runnable{
   public boolean flag;
   Ticket(boolean flag){
      this.flag = flag;
   }
   Ticket(){
      flag=true;
   }
   public void run(){
       if(flag){
	      synchronized(MyLock.lockA){
		      System.out.println(Thread.currentThread().getName() + " lockA &&--->lockB");
			  try{
		         Thread.sleep(100);
		      }catch(InterruptedException e){
		      }
			  synchronized(MyLock.lockB){
			       System.out.println(Thread.currentThread().getName() + " lockB");
			  }
		  }
	   }
	   else{
	      synchronized(MyLock.lockB){
		      System.out.println(Thread.currentThread().getName() + " lockB &&--->lockA");
			  synchronized(MyLock.lockA){
			       System.out.println(Thread.currentThread().getName() + " lockA");
			  }
		  }
	   }
   }
}

class MyLock{
   public static final MyLock lockA = new MyLock();
   public static final MyLock lockB = new MyLock();
}

public class DeadLockDemo{
   public static void main(String[] args){
   //虽然new了两个任务对象,但是不影响演示由于同步嵌套引起的死锁情况
   //    new Thread(new Ticket(true)).start();
   //    new Thread(new Ticket(false)).start();
   
   ///////////////////////////////////////////////////////////
   
        Ticket tt = new Ticket();//只产生一个线程任务!这样写还要控制好sleep的时间才好.....
        new Thread(tt).start();
		try{
		   Thread.sleep(20);
		}catch(InterruptedException e){
		}
		tt.flag=false;
        new Thread(tt).start();
   }
}

  

java中同步嵌套引起的死锁事例代码,布布扣,bubuko.com

java中同步嵌套引起的死锁事例代码

上一篇:Best Time to Buy and Sell Stock III leetcode java


下一篇:Maximum Subarray leetcode java