Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms; namespace WinLock
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void btn_Start_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
Thread[] threads = new Thread[];//使用new关键字在堆里创建对象,其生命期相当于全局变量,但访问的时候与普通变量一样
Account acc = new Account(, this);
for (int i = ; i < ; i++)
{
Thread t = new Thread(acc.DoTransactions);
t.Name = "线程" + i;
threads[i] = t;
}
for (int i = ; i < ; i++)
{
threads[i].Start();
}
} delegate void AddListBoxItemDelegate(string str);//在类的内部也能声明代理
public void AddListBoxItem(string str)
{
if (listBox1.InvokeRequired)//如果是跨线程访问控件则为true
{
AddListBoxItemDelegate d = AddListBoxItem;//代理
listBox1.Invoke(d, str);//调用代理函数并传递参数
}
else
{
listBox1.Items.Add(str);//不是跨线程访问控件则直接访问该控件
}
} }
}

account.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace WinLock
{
public class Account
{
private Object lockedObj = new Object();
int balance;
Random r = new Random();
Form1 form1;
public Account(int initial, Form1 form1)
{
this.form1 = form1;
this.balance = initial;
}
/// <summary>
/// 取款
/// </summary>
/// <param name="amount">取款金额</param>
/// <returns>余额</returns>
private int Withdraw(int amount)
{
if (balance < )
{
form1.AddListBoxItem("余额:" + balance + " 已经为负值了,还想取呵!");
} //将lock (lockedObj)这句注释掉,看看会发生什么情况
lock (lockedObj)
{
if (balance >= amount)
{
string str = Thread.CurrentThread.Name + "取款---";
str += string.Format("取款前余额:{0,-6}取款:{1,-6}", balance, amount);
balance = balance - amount;
str += "取款后余额:" + balance;
form1.AddListBoxItem(str);
return amount;
}
else
{
return ;
}
}
}
/// <summary>自动取款</summary>
public void DoTransactions()//Transaction--事务
{
for (int i = ; i < ; i++)
{
Withdraw(r.Next(, ));
}
} }
}

不加lock 会出现统一资源被多次利用的情况

最新文章

  1. Codeforces 486E LIS of Sequence 题解
  2. SSIS的 Data Flow 和 Control Flow
  3. CodeUI Test:UIMap录制文件分析一
  4. Windows 10通过本地镜像离线安装.NET 3.5
  5. SVN使用总结
  6. python 使用字符串名调用类以及调用类方法名
  7. CSS的样式表基本概念
  8. 显示XML文档时排序数据
  9. T4 模板 : 一种提升ASP.NET MVC开发速度方法
  10. swfit-block反向传值
  11. 2d网络游戏的延迟补偿(Lag compensation with networked 2D games)
  12. SQL Server里的 ISNULL 与 NULLIF
  13. Axure自动幻灯片制作
  14. .net中的4种事务总结
  15. Android Oreo 8.0 新特性实战 Autosizing TextView --自动缩放TextView
  16. Redis相关指令文档
  17. linux 服务发布脚本升级,远程发布,指定拉取远程dev,test等分支代码
  18. linux nginx 基本用法
  19. python - 自定制property/property的延时计算
  20. vnc操作指南

热门文章

  1. git 回滚指定行
  2. C#在WinForm下使用HttpWebRequest上传文件
  3. js中级小知识1
  4. itoa()、atoi()、任意进制转换
  5. mysql提权常用方法。 hack某某
  6. Consul部署架构
  7. mysql-proxy 简介
  8. Pandas的可视化操作(利用pandas得到图表)
  9. python之以字符串形式导入模块
  10. js map()与forEach()的用法与区别