运行环境: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());}}}}