C#通过Semaphore类控制线程队列的方法
本文实例讲述了C#通过Semaphore类控制线程队列的方法。分享给大家供大家参考。具体实现方法如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.IO;
usingSystem.Diagnostics;
usingSystem.Threading;
usingSystem.ComponentModel;
usingSystem.Collections;
usingSystem.Net;
usingSystem.Runtime.Serialization;
usingSystem.Xml;
usingSystem.Globalization;
usingSystem.Text.RegularExpressions;
usingSystem.Data;
usingSystem.Data.SqlClient;
namespaceConsoleApp
{
///<summary>
///线程控制队列
///Semaphore类
///</summary>
classProgram
{
staticSemaphoresemaphore;
staticvoidMain(string[]args)
{
semaphore=newSemaphore(0,2);
Threadthread;
for(inti=0;i<=5;i++)
{
thread=newThread(newParameterizedThreadStart(Run));
thread.Start("thread_"+i.ToString());
}
semaphore.Release(2);
Console.ReadLine();
}
staticvoidRun(objectobj)
{
semaphore.WaitOne();
Console.WriteLine("thread"+obj.ToString()+"intothemethod");
System.Threading.Thread.Sleep(5000);
Console.WriteLine("_thread"+obj.ToString()+"leavethemethod");
semaphore.Release();
}
}
}
希望本文所述对大家的C#程序设计有所帮助。