码迷,mamicode.com
首页 > 其他好文 > 详细

写一个死锁

时间:2018-06-03 19:29:56      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:system   out   art   oid   不同的   new   read   ati   -o   

死锁产生的原因:

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

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

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

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

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();
  }

}

写一个死锁

标签:system   out   art   oid   不同的   new   read   ati   -o   

原文地址:https://www.cnblogs.com/shenhengjia/p/9129779.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!