zoukankan      html  css  js  c++  java
  • 写一个死锁

    死锁产生的原因:

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

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

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

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

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

    }

  • 相关阅读:
    深入了解Struts2返回JSON数据的原理及具体应用范例
    Struts国际化
    LeetCode Balanced Binary Tree
    LeetCode Triangle
    Binary Tree Level Order Traversal
    Pow(x,n)
    Symmetric Tree
    LeetCode Word Search
    LeetCode Insert Interval
    Maximum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/shenhengjia/p/9129779.html
Copyright © 2011-2022 走看看