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

    }

  • 相关阅读:
    嵌入式操作系统-小型任务调度的理解(转)
    数据分析-pandas基础入门(一)
    硬件电路设计——低通滤波器的应用
    Docker
    AWK总结
    DNS解析
    TCP/IP
    Mysql优化部分总结
    Nginx配置文件释义备查
    时间模块
  • 原文地址:https://www.cnblogs.com/shenhengjia/p/9129779.html
Copyright © 2011-2022 走看看