zoukankan      html  css  js  c++  java
  • 线程访问临界区的问题 实例,需解决

    using System;
    using System.Threading;

    namespace LockAndThread
    {
     /// <summary>
     /// Class1 的摘要说明。
     /// </summary>
     class Test
     {
      /// <summary>
      /// 应用程序的主入口点。
      /// </summary>

      static Thread[] threads=new Thread[10];
      static void Main(string[] args)
      {
       Account acc=new Account(0);
       for(int i=0;i<10;i++)
       {
        Thread t=new Thread(new ThreadStart(acc.DoTransactions));
        threads[i]=t;
       }
       for(int i=0;i<10;i++)
       {
        threads[i].Start();
       }
       Console.WriteLine("The threads is running !");
       Console.Read();

      }
     }


     class Account
     {
      int balance;
      Random r=new Random();

      public Account(int initial)
      {
       balance=initial;
      }
      int Withdraw(int amount)
      {
       if (balance<0)
       {
        throw new Exception("Banlance已经为负数了!");
       }
       Console.WriteLine("The main thread output the current balance is "+balance);
       //return UseLock(amount);
      return UseInterLock(amount);
    //    return UseMonitor(amount);
      }

      int UseLock(int amount)
      {
       lock(this)
       {
        if (balance>=amount)
        {
         Thread.Sleep(5);
         balance=balance-amount;
         return amount;
        }
        else
        {
         return 0;//transaction reject
        }
       }
      }

      int UseInterLock(int amount)
      { 
       if (balance>=amount)
       {
        int nOld=balance-amount;
        Thread.Sleep(5);
        balance=balance-amount;
        Interlocked.CompareExchange(ref balance,nOld,nOld);
        return amount;
       }
       else
       {
        return 0;
       }

      }
      int UseMonitor(int amount)
      {
    //   try
    //   {
        //I,不限时的访问
    //    Monitor.Enter(this);
        
        
        //II.在指定的时间里获取排他锁来执行
    //    if (Monitor.TryEnter(this,TimeSpan.FromSeconds(30)))
    //     //30秒内获取对象排他锁
        {
         if (balance>=amount)
         {
          Thread.Sleep(5);
          balance=balance-amount;
          return amount;
         }
         else
         {
          return 0;
         }

    //    }
    //
    //   }
    //   catch
    //   {
    //    //the
    //   }


      }

      public void DoTransactions()
      {
       for(int i=0;i<10;i++)
       {
        Withdraw(r.Next(-50,100));
       }
      }
     }
    }

  • 相关阅读:
    网络安全等级保护系统定级流程与示例
    分析设计之类图
    分析设计中用例图、类图与时序图关系
    工业网络安全产品应用场景
    网络安全拟态防御技术
    浅说:网络空间拟态防御是个什么鬼?
    邬江兴院士:鲁棒控制与内生安全
    邬江兴院士:工业互联网安全&拟态防御
    邬江兴院士:多模态智慧网络与内生安全
    Samba CVE-2017-7494验证实验
  • 原文地址:https://www.cnblogs.com/itelite/p/990487.html
Copyright © 2011-2022 走看看