C#关于多线程及线程同步
来源:互联网 发布:php 字符串分割 编辑:程序博客网 时间:2024/06/15 14:50
Form1.cs
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Threading;//包含头文件namespace lockExample{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { listBox1.Items.Clear(); Thread[] threads = new Thread[10];//使用new关键字在堆里创建对象,其生命期相当于全局变量,但访问的时候与普通变量一样 Account acc = new Account(1000, this); for (int i = 0; i < 10; i++) { Thread t = new Thread(acc.DoTransactions); t.Name = "线程" + i; threads[i] = t; } for (int i = 0; i < 10; 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.Text;using System.Windows.Forms;using System.Threading;namespace lockExample{ 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 < 0) { 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 0; } } } /// <summary>自动取款</summary> public void DoTransactions()//Transaction--事务 { for (int i = 0; i < 100; i++) { Withdraw(r.Next(1, 100)); } } }}
- C#关于多线程及线程同步
- MFC 多线程及线程同步
- MFC 多线程及线程同步
- MFC 多线程及线程同步
- MFC多线程及线程同步
- MFC 多线程及线程同步
- MFC 多线程及线程同步
- MFC 多线程及线程同步
- MFC 多线程及线程同步
- MFC 多线程及线程同步
- MFC 多线程及线程同步
- MFC 多线程及线程同步
- MFC 多线程及线程同步
- MFC 多线程及线程同步
- MFC 多线程及线程同步
- MFC 多线程及线程同步
- MFC 多线程及线程同步
- MFC 多线程及线程同步
- 在linux下设置开机自动启动程序的方法[转]
- CentOS6.2下一步一步源代码安装OpenStack(九)Swift存储节点安装、配置及运行
- 带互斥的消息队列C++
- KVM/QEMU桥接网络设置
- <s:textfield>标签的tr问题
- C#关于多线程及线程同步
- 下载KVM
- javascript正则表达式
- DataGridView用法总结
- jvm crash 异常代码如何分析
- SQL 在OPENQUERY中使用传入参数和临时表获取参数
- 覆盖和重载
- 内敛元素和块元素区别
- windows 7 下安装Oracle 9i 解决方法