C#线程队列用法实例分析
本文实例讲述了C#线程队列用法。分享给大家供大家参考。具体如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Threading; namespaceThreadPro { classProgram { staticMutexgM1; staticMutexgM2; constintITERS=100; staticAutoResetEventEvent1=newAutoResetEvent(false); staticAutoResetEventEvent2=newAutoResetEvent(false); staticAutoResetEventEvent3=newAutoResetEvent(false); staticAutoResetEventEvent4=newAutoResetEvent(false); staticvoidMain(string[]args) { Console.WriteLine("MutexSample"); //创建一个Mutex对象,并且命名为MyMutex gM1=newMutex(true,"MyMutex"); //创建一个未命名的Mutex对象. gM2=newMutex(true); Console.WriteLine("-MainOwnsgM1andgM2"); AutoResetEvent[]evs=newAutoResetEvent[4]; evs[0]=Event1;//为后面的线程t1,t2,t3,t4定义AutoResetEvent对象 evs[1]=Event2; Programtm=newProgram(); Threadt1=newThread(newThreadStart(tm.t1Start)); Threadt2=newThread(newThreadStart(tm.t2Start)); Threadt3=newThread(newThreadStart(tm.t3Start)); Threadt4=newThread(newThreadStart(tm.t4Start)); t1.Start();//使用Mutex.WaitAll()方法等待一个Mutex数组中的对象全部被释放 t2.Start();//使用Mutex.WaitOne()方法等待gM1的释放 t3.Start();//使用Mutex.WaitAny()方法等待一个Mutex数组中任意一个对象被释放 t4.Start();//使用Mutex.WaitOne()方法等待gM2的释放 Thread.Sleep(2000); Console.WriteLine("-MainreleasesgM1"); gM1.ReleaseMutex();//线程t2,t3结束条件满 Thread.Sleep(1000); Console.WriteLine("-MainreleasesgM2"); gM2.ReleaseMutex();//线程t1,t4结束条件满足 //等待所有四个线程结束 WaitHandle.WaitAll(evs); Console.WriteLine("MutexSample"); Console.ReadLine(); } publicvoidt1Start() { Console.WriteLine("方法一运行,Mutex.WaitAll(Mutex[])"); Mutex[]gMs=newMutex[2]; gMs[0]=gM1;//创建一个Mutex数组作为Mutex.WaitAll()方法的参数 gMs[1]=gM2; Mutex.WaitAll(gMs);//等待gM1和gM2都被释放 gM1.ReleaseMutex();//修正上一次出现的错误 gM2.ReleaseMutex();//修正上一次出现的错误 Thread.Sleep(2000); Console.WriteLine("方法一完毕,WaitAll(Mutex[])satisfied"); Event1.Set();//线程结束,将Event1设置为有信号状态 } publicvoidt2Start() { Console.WriteLine("方法二运行,gM1.WaitOne()"); gM1.WaitOne();//等待gM1的释放 gM1.ReleaseMutex();//修正上一次出现的错误 Console.WriteLine("方法二完毕,gM1.WaitOne()satisfied"); Event2.Set();//线程结束,将Event2设置为有信号状态 } publicvoidt3Start() { Console.WriteLine("t3Startstarted,Mutex.WaitAny(Mutex[])"); Mutex[]gMs=newMutex[2]; gMs[0]=gM1;//创建一个Mutex数组作为Mutex.WaitAny()方法的参数 gMs[1]=gM2; Mutex.WaitAny(gMs);//等待数组中任意一个Mutex对象被释放 gM1.ReleaseMutex();//修正上一次出现的错误 Console.WriteLine("t3Startfinished,Mutex.WaitAny(Mutex[])"); Event3.Set();//线程结束,将Event3设置为有信号状态 } publicvoidt4Start() { Console.WriteLine("t4Startstarted,gM2.WaitOne()"); gM2.WaitOne();//等待gM2被释放 gM2.ReleaseMutex();//修正上一次出现的错误 Console.WriteLine("t4Startfinished,gM2.WaitOne()"); Event4.Set();//线程结束,将Event4设置为有信号状态 } } }
希望本文所述对大家的C#程序设计有所帮助。