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

  • 相关阅读:
    三种钱是花的越多,赚的越多
    程序员除去繁华,你的匠心何在?
    科目三考试
    药房托管
    文章标题
    【cocos2d-x 3.7 飞机大战】 决战南海I (八) 背景移动
    Android开发时经经常使用的LogUtil
    仿支付宝/微信的password输入框效果GridPasswordView解析
    hdoj 1518 Square 【dfs】
    mysql配置文件夹错误:在安装mysql 5.6.19 时运行cmake命令是出现CMake Error: The source directory does not appear to contai
  • 原文地址:https://www.cnblogs.com/itelite/p/990487.html
Copyright © 2011-2022 走看看