写一个死锁

死锁产生的原因:

一个线程进入锁一需要锁二,

另一个线程进入锁二需要锁一,

由于锁一锁二都被占了,所以线程执行不下去。

所以只需写一个相互交叉的锁一锁二就可以产生死锁。

class sisuogoucheng implements Runnable
{
  private boolean panduan=true;

  sisuogoucheng(boolean panduan)
  {
    this.panduan=panduan;  //写一个判断条件使线程进入不同的锁。
  }


  public void run()

  {    

    if(panduan)

    {
      synchronized(mykey.obj1)
      {
        System.out.println("t1----obj1");
        synchronized(mykey.obj2)
        {
          System.out.println("t1------obj2");
        }
      }
    }
    else
    {
      synchronized(mykey.obj2)
      {
        System.out.println("t2-------obj2");
        synchronized(mykey.obj1)
        {
          System.out.println("t2---------obj1");
        }
      }
    }
  }
}

class mykey
{
  static Object obj1=new Object();  //创建两个不同的锁
  static Object obj2=new Object();
}

public class sisuo

{

  public static void main(String[] args)

   {

    Thread t1=new Thread(new sisuogoucheng(true));
    Thread t2=new Thread(new sisuogoucheng(false));

    t1.start();
    t2.start();
  }

}

猜你喜欢

转载自www.cnblogs.com/shenhengjia/p/9129779.html