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

  • 相关阅读:
    win10快速搭建git服务
    java字节流转对象,应用于协议解析
    产品设计-后台管理权限设计RBAC
    Git :fatal: 错误提示解决办法
    初学git,出现错误:fatal: Not a git repository (or any of the parent directories): .git
    css 清除浮动
    asp.net连接SQL SERVER 2012的方法
    c#的序列化与反序列化
    .NET三层架构例子超链接可以点击显示内容页面
    ASP.NET中iframe框架点击左边页面链接,右边显示链接页面内容
  • 原文地址:https://www.cnblogs.com/itelite/p/990487.html
Copyright © 2011-2022 走看看