C#多线程-模拟火车票卖票程序

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

运行环境:VS2008C#控制台程序描述:运用多线程模拟火车票的卖票程序,多个售票点同时销售一个车次的票,即多个线程同时操作一个变量,运用了AutoResetEvent来控制同步。代码很简单,希望能给新手一点启发。usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;namespaceSalingTickets{classClass1{staticAutoResetEventm_are=newAutoResetEvent(false);//实例化一个控制同步的对象staticinttickets=100;//定义全局变量,即票数staticvoidMain(string[]args)//主函数{Threadt1=newThread(newThreadStart(Th1));Threadt2=newThread(newThreadStart(Th2));Threadt3=newThread(newThreadStart(Th3));Threadt4=newThread(newThreadStart(Th4));t1.Name=1;t2.Name=2;t3.Name=3;t4.Name=4;t1.Start();t2.Start();t3.Start();t4.Start();m_are.Set();//开始线程Console.ReadLine();}//一个售票点一个线程staticvoidTh1(){m_are.WaitOne();Thread.Sleep(10);Saling();}staticvoidTh2(){m_are.WaitOne();Thread.Sleep(10);Saling();}staticvoidTh3(){m_are.WaitOne();Thread.Sleep(10);Saling();}staticvoidTh4(){m_are.WaitOne();Thread.Sleep(10);Saling();}//卖票函数staticvoidSaling(){Threadthr=Thread.CurrentThread;try{while(tickets-1){Console.WriteLine(Thread+thr.Name+issaling+tickets--);m_are.Set();Thread.Sleep(100);}}catch(ThreadStartExceptionte){Console.WriteLine(te.ToString());}}}}

1 / 2
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功