线程访问临界区的问题 实例,需解决

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

原文地址:https://www.cnblogs.com/itelite/p/990487.html