C#线程队列用法实例分析
程序员文章站
2023-11-22 14:13:22
本文实例讲述了c#线程队列用法。分享给大家供大家参考。具体如下:
using system;
using system.collections.generic;...
本文实例讲述了c#线程队列用法。分享给大家供大家参考。具体如下:
using system; using system.collections.generic; using system.text; using system.threading; namespace threadpro { class program { static mutex gm1; static mutex gm2; const int iters = 100; static autoresetevent event1 = new autoresetevent(false); static autoresetevent event2 = new autoresetevent(false); static autoresetevent event3 = new autoresetevent(false); static autoresetevent event4 = new autoresetevent(false); static void main(string[] args) { console.writeline("mutex sample "); //创建一个mutex对象,并且命名为mymutex gm1 = new mutex(true, "mymutex"); //创建一个未命名的mutex 对象. gm2 = new mutex(true); console.writeline(" - main owns gm1 and gm2"); autoresetevent[] evs = new autoresetevent[4]; evs[0] = event1; //为后面的线程t1,t2,t3,t4定义autoresetevent对象 evs[1] = event2; program tm = new program(); thread t1 = new thread(new threadstart(tm.t1start)); thread t2 = new thread(new threadstart(tm.t2start)); thread t3 = new thread(new threadstart(tm.t3start)); thread t4 = new thread(new threadstart(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(" - main releases gm1"); gm1.releasemutex(); //线程t2,t3结束条件满 thread.sleep(1000); console.writeline(" - main releases gm2"); gm2.releasemutex(); //线程t1,t4结束条件满足 //等待所有四个线程结束 waithandle.waitall(evs); console.writeline(" mutex sample"); console.readline(); } public void t1start() { console.writeline("方法一运行, mutex.waitall(mutex[])"); mutex[] gms = new mutex[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设置为有信号状态 } public void t2start() { console.writeline("方法二运行, gm1.waitone( )"); gm1.waitone();//等待gm1的释放 gm1.releasemutex(); //修正上一次出现的错误 console.writeline("方法二完毕, gm1.waitone( ) satisfied"); event2.set();//线程结束,将event2设置为有信号状态 } public void t3start() { console.writeline("t3start started, mutex.waitany(mutex[])"); mutex[] gms = new mutex[2]; gms[0] = gm1;//创建一个mutex数组作为mutex.waitany()方法的参数 gms[1] = gm2; mutex.waitany(gms);//等待数组中任意一个mutex对象被释放 gm1.releasemutex(); //修正上一次出现的错误 console.writeline("t3start finished, mutex.waitany(mutex[])"); event3.set();//线程结束,将event3设置为有信号状态 } public void t4start() { console.writeline("t4start started, gm2.waitone( )"); gm2.waitone();//等待gm2被释放 gm2.releasemutex(); //修正上一次出现的错误 console.writeline("t4start finished, gm2.waitone( )"); event4.set();//线程结束,将event4设置为有信号状态 } } }
希望本文所述对大家的c#程序设计有所帮助。