C#多线程Lock锁定的使用例子(多线程线程同步)

这个例子是一个模拟多个人在多台提款机上同时提取一个账户的款的情况。

在存取的过程中 可能 A线程取了100   而B线程那边还看见账户上没少掉那100快,所以导致数据不统一,赋值出现问题。

下面代码则可以测试出加上Lock锁定 与 不加的区别。

 

先上两个图。

第一个(加了Lock的程序):

 

加了的 数据每一条都是完整无错的,因为他们执行Lock包含的代码时,是一个线程一个线程的执行,而不是一拥而上 都在混乱的执行,那变量就会造成不稳定的情况。

 

下面是不加Lock的代码。

仔细看选中行 与 下一行的余额数目。。

按理说下一行 余额应该是509的,可是 却条到了下下行。。10个线程都在取钱 对变量进行操作。。所以会出现这个问题。

 

这就是Lock的好处。

下面贴代码

 

Form1窗体代码

引入命名控件:

[csharp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. using System.Threading;  


完整代码:

[csharp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. namespace ThreadExample  
  2. {  
  3.     public partial class Form1 : Form  
  4.     {  
  5.         Thread thread1, thread2;  
  6.         Class1 class1;  
  7.         public Form1()  
  8.         {  
  9.             InitializeComponent();  
  10.             class1 = new Class1(this);  
  11.         }  
  12.   
  13.         private void btn_Start_Click(object sender, EventArgs e)  
  14.         {  
  15.             txt_Text.Text = "";  
  16.             class1.shouldStop = false;  
  17.             thread1 = new Thread(class1.Method1);  
  18.             thread1.IsBackground = true;  
  19.             thread2 = new Thread(class1.Method2);  
  20.             thread2.IsBackground = true;  
  21.             thread1.Start("a method start\n");  
  22.             thread2.Start();  
  23.         }  
  24.   
  25.         private delegate void AddMessageDelegate(string message);  
  26.         public void AddMessage(string message)  
  27.         {  
  28.             if (txt_Text.InvokeRequired)  
  29.             {  
  30.                 AddMessageDelegate d = AddMessage;  
  31.                 txt_Text.Invoke(d, message);  
  32.             }  
  33.             else  
  34.                 txt_Text.AppendText(message);  
  35.         }  
  36.   
  37.         private void btn_Stop_Click(object sender, EventArgs e)  
  38.         {  
  39.             class1.shouldStop = true;  
  40.             thread1.Join(0);  
  41.             thread2.Join(0);  
  42.         }  
  43.     }  
  44. }  


 

 

Account.cs代码:

引入命名空间:

[csharp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. using System.Threading;  


完整代码:

[csharp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. namespace LockExample  
  2. {  
  3.     class Account  
  4.     {  
  5.         private object lockObj = new object();  
  6.         int balance;    //余额  
  7.         Random r = new Random();  
  8.         Form1 form1;  
  9.         public Account(int initial, Form1 form1)  
  10.         {  
  11.             this.form1 = form1;  
  12.             this.balance = initial;  
  13.         }  
  14.   
  15.         /// <summary>  
  16.         /// 取款  
  17.         /// </summary>  
  18.         /// <param name="amount">取款金额</param>  
  19.         /// <returns>余额</returns>  
  20.         private int Withdraw(int amount)  
  21.         {  
  22.             if (balance < 0)  
  23.                 form1.AddListBoxItem("余额:" + balance + " 已经为负值了,还想取呵!");  
  24.             //lock (lockObj)  
  25.             {  
  26.                 if (balance >= amount)  
  27.                 {  
  28.                     string str = Thread.CurrentThread.Name + "取款---";  
  29.                     str += string.Format("取款前余额:{0,-6}取款:{1,-6}", balance, amount);  
  30.                     balance = balance - amount;  
  31.                     str += "取款后余额:" + balance;  
  32.                     form1.AddListBoxItem(str);  
  33.                     return amount;  
  34.                 }  
  35.                 else  
  36.                     return 0;  
  37.             }  
  38.         }  
  39.   
  40.         /// <summary>  
  41.         /// 自动取款  
  42.         /// </summary>  
  43.         public void DoTransactions()  
  44.         {  
  45.             for (int i = 0; i < 100; i++)  
  46.             {  
  47.                 Withdraw(r.Next(1,100));  
  48.             }  
  49.         }  
  50.     }  
  51. }  


参考:http://www.wxzzz.com/Program/ThreadLock

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值