C#多线程经典示例(吃苹果)
程序员文章站
2022-03-04 20:09:10
本文主要讲述了多线程开发中经典示例,通过本示例,可以加深对多线程的理解。
示例概述:
下面用一个模拟吃苹果的实例,说明c#中多线程的实现方法。要求开发一个程序实现如下情...
本文主要讲述了多线程开发中经典示例,通过本示例,可以加深对多线程的理解。
示例概述:
下面用一个模拟吃苹果的实例,说明c#中多线程的实现方法。要求开发一个程序实现如下情况:一个家庭有三个孩子,爸爸妈妈不断削苹果往盘子里面放,老大、老二、老三不断从盘子里面取苹果吃。盘子的大小有限,最多只能放5个苹果,并且爸妈不能同时往盘子里面放苹果,妈妈具有优先权。三个孩子取苹果时,盘子不能为空,三人不能同时取,老三优先权最高,老大最低。老大吃的最快,取的频率最高,老二次之。
涉及到知识点:
- 线程thread 创建并控制线程,设置其优先级并获取其状态。
- 锁 lock 用于实现多线程同步的最直接办法就是加锁,它可以把一段代码定义为互斥段,在一个时刻内只允许一个线程进入执行,而其他线程必须等待。
- 事件eventhandler 声明一个事件,用于通知界面做改变
设计思路:
- productor 表示生产者,用于削苹果。
- consumer 表示消费者,用于吃苹果。
- dish 盘子,用于装苹果,做为中间类
- eatapplesmp 的begineat()方法,表示开始吃苹果,启动线程
效果图如下【爸爸妈妈削苹果,孩子吃苹果】:
后台输出如下:
mama放1个苹果 baba放1个苹果 dage取苹果吃... erdi取苹果吃... sandi等待取苹果 mama放1个苹果 sandi取苹果吃... baba放1个苹果 dage取苹果吃... mama放1个苹果 baba放1个苹果 erdi取苹果吃... mama放1个苹果 baba放1个苹果 dage取苹果吃... sandi取苹果吃... mama放1个苹果 baba放1个苹果 erdi取苹果吃... mama放1个苹果 baba放1个苹果 dage取苹果吃... mama放1个苹果 baba放1个苹果 sandi取苹果吃... mama放1个苹果 baba正在等待放入苹果 erdi取苹果吃... baba放1个苹果 dage取苹果吃... mama放1个苹果 baba正在等待放入苹果 mama正在等待放入苹果 sandi取苹果吃... baba放1个苹果 mama正在等待放入苹果 erdi取苹果吃... mama放1个苹果 dage取苹果吃... baba放1个苹果 mama正在等待放入苹果 dage取苹果吃... mama放1个苹果 baba正在等待放入苹果 erdi取苹果吃... baba放1个苹果 sandi取苹果吃... mama放1个苹果 baba正在等待放入苹果 dage取苹果吃... baba放1个苹果 mama正在等待放入苹果 erdi取苹果吃... mama放1个苹果 baba正在等待放入苹果 sandi取苹果吃... baba放1个苹果 mama正在等待放入苹果 dage取苹果吃... mama放1个苹果 baba正在等待放入苹果 mama正在等待放入苹果 erdi取苹果吃... mama放1个苹果 baba正在等待放入苹果 dage取苹果吃... baba放1个苹果 mama正在等待放入苹果 sandi取苹果吃... mama放1个苹果 baba正在等待放入苹果 mama正在等待放入苹果 线程 'mama' (0x1ce0) 已退出,返回值为 0 (0x0)。 线程 'baba' (0x1888) 已退出,返回值为 0 (0x0)。 erdi取苹果吃... dage取苹果吃... sandi取苹果吃... dage取苹果吃... erdi取苹果吃... dage等待取苹果 sandi等待取苹果 erdi等待取苹果 后台输出
productor 代码如下:
using system; using system.collections.generic; using system.linq; using system.text; using system.threading; namespace demosharp.eatapple { /// <summary> /// 生产者 /// </summary> public class productor { private dish dish; private string name; public string name { get { return name; } set { name = value; } } public eventhandler putaction;//声明一个事件,当放苹果时触发该事件 public productor(string name, dish dish) { this.name = name; this.dish = dish; } public void run() { while (true) { bool flag= dish.put(name); if (flag) { if (putaction != null) { putaction(this, null); } try { thread.sleep(600);//削苹果时间 } catch (exception ex) { } } else { break; } } } } }
consumer代码如下:
using system; using system.collections.generic; using system.linq; using system.text; using system.threading; namespace demosharp.eatapple { /// <summary> /// 消费者 /// </summary> public class consumer { private string name; public string name { get { return name; } set { name = value; } } private dish dish; private int timelong; public eventhandler getaction;//声明一个事件,当放苹果时触发该事件 public consumer(string name, dish dish, int timelong) { this.name = name; this.dish = dish; this.timelong = timelong; } public void run() { while (true) { bool flag= dish.get(name); if (flag) { //如果取到苹果,则调用事件,并开始吃 if (getaction != null) { getaction(this, null); } try { thread.sleep(timelong);//吃苹果时间 } catch (threadinterruptedexception) { } } else { break; } } } } }
dish代码如下:
using system; using system.collections.generic; using system.linq; using system.text; using system.threading; namespace demosharp.eatapple { /// <summary> /// 盘子,属于中间类 /// </summary> public class dish { private int f = 5;//表示盘子中还可以放几个苹果,最多只能放5个苹果 private int enablednum;//可放苹果总数 private int n = 0; //表示已经放了多少个苹果 private object objget = new object(); private object objput = new object(); /// <summary> /// 构造函数,初始化dish对象 /// </summary> /// <param name="num">表示削够多少个苹果结束</param> public dish(int num) { this.enablednum = num; } /// <summary> /// 放苹果的方法 /// </summary> /// <param name="name"></param> ///<returns>是否放成功</returns> public bool put(string name) { lock (this)//同步控制放苹果 { bool flag = false; while (f == 0)//苹果已满,线程等待 { try { system.console.writeline(name + "正在等待放入苹果"); monitor.wait(this); } catch (exception ex) { system.console.writeline(name + "等不及了"); } } if (n < enablednum) { f = f - 1;//削完一个苹果放一次 n = n + 1; system.console.writeline(name + "放1个苹果"); flag = true; } monitor.pulseall(this); return flag; } } /// <summary> /// 取苹果的方法 /// </summary> /// <param name="name"></param> public bool get(string name) { lock (this)//同步控制取苹果 { bool flag = false; while (f == 5) { try { system.console.writeline(name + "等待取苹果"); monitor.wait(this); } catch (threadinterruptedexception) { } } if (n <= enablednum) { f = f + 1; system.console.writeline(name + "取苹果吃..."); flag = true; } monitor.pulseall(this); return flag; } } } }
eatapplesmp代码如下:
using system; using system.collections.generic; using system.linq; using system.text; using system.threading; namespace demosharp.eatapple { public class eatapplesmp { public eventhandler putaction;//声明一个事件,当放苹果时触发该事件 public eventhandler getaction;//声明一个事件,当放苹果时触发该事件 /// <summary> /// 开始吃苹果 /// </summary> public void begineat() { thread th_mother, th_father, th_young, th_middle, th_old;//依次表示妈妈,爸爸,小弟,二弟,大哥 dish dish = new dish(30); productor mother = new productor("mama", dish);//建立线程 mother.putaction += putactionmethod; productor father = new productor("baba", dish); father.putaction += putactionmethod; consumer old = new consumer("dage", dish, 1200); old.getaction += getactionmethod; consumer middle = new consumer("erdi", dish, 1500); middle.getaction += getactionmethod; consumer young = new consumer("sandi", dish, 1800); young.getaction += getactionmethod; th_mother = new thread(new threadstart(mother.run)); th_mother.name = "mama"; th_father = new thread(new threadstart(father.run)); th_father.name = "baba"; th_old = new thread(new threadstart(old.run)); th_old.name = "dage"; th_middle = new thread(new threadstart(middle.run)); th_middle.name = "erdi"; th_young = new thread(new threadstart(young.run)); th_young.name = "sandi"; th_mother.priority = threadpriority.highest;//设置优先级 th_father.priority = threadpriority.normal; th_old.priority = threadpriority.lowest; th_middle.priority = threadpriority.normal; th_young.priority = threadpriority.highest; th_mother.start(); th_father.start(); th_old.start(); th_middle.start(); th_young.start(); } private void getactionmethod(object sender,eventargs e) { if (getaction != null) { getaction(sender, e); } } private void putactionmethod(object sender, eventargs e) { if (putaction != null) { putaction(sender, e); } } } }
界面类代码如下:
using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; using demosharp.eatapple; namespace demosharp { /// <summary> /// 页面类 /// </summary> public partial class eatappleform : form { private eatapplesmp m_eatapplesmp = new eatapplesmp(); public eatappleform() { initializecomponent(); initview(); m_eatapplesmp.putaction += putactionmethod; m_eatapplesmp.getaction += getactionmethod; } /// <summary> /// 初始化groupbox /// </summary> private void initview() { this.gbbaba.controls.clear(); this.gbmama.controls.clear(); this.gbdage.controls.clear(); this.gberdi.controls.clear(); this.gbsandi.controls.clear(); } /// <summary> /// 启动线程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnstart_click(object sender, eventargs e) { this.m_eatapplesmp.begineat(); } /// <summary> /// 放苹果事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void putactionmethod(object sender, eventargs e) { productor p = sender as productor; if (p != null) { if (p.name == "baba") { additemtogroupbox(this.gbbaba, this.lblbaba); } if (p.name == "mama") { additemtogroupbox(this.gbmama, this.lblmama); } } } /// <summary> /// 吃苹果事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void getactionmethod(object sender, eventargs e) { consumer c = sender as consumer; if (c != null) { if (c.name == "dage") { additemtogroupbox(this.gbdage, this.lbldage); } if (c.name == "erdi") { additemtogroupbox(this.gberdi, this.lblerdi); } if (c.name == "sandi") { additemtogroupbox(this.gbsandi, this.lblsandi); } } } /// <summary> /// 往指定的groupbox中添加对象 /// </summary> /// <param name="gbview"></param> /// <param name="lbl"></param> private void additemtogroupbox(groupbox gbview,label lbl) { gbview.invoke(new action(() => { picturebox p = new picturebox(); p.width = 20; p.height = 20; p.dock = dockstyle.left; p.image = this.imglst01.images[0]; p.margin = new padding(2); gbview.controls.add(p); })); //显示个数 lbl.invoke(new action(() => { if (string.isnullorempty(lbl.text)) { lbl.text = "0"; } lbl.text = (int.parse(lbl.text) + 1).tostring(); })); } } }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!
上一篇: Redis字符串对象实用笔记
下一篇: redis单线程快的原因和原理