如果设计一个服务器程序,每当处理用户请求时,都开始一个线程,将会在一定程序上消耗服务器的资源。为此,一个最好的解决方法就是在服务器启动之前,事先创建一些线程对象,然后,当处理客户端请求时,就从这些建好的线程中获得线程对象,并处理请求。保存这些线程对象的结构就叫做线程池。
代码:
public class ClsThreadPool
{
public static void Main()
{//线程池类 ThreadPool;WaitCallback委托
Console.WriteLine("以下开始将工作排入线程管理工作队列!!");
Console.WriteLine("***************");
//资源分配更合理
//ThreadPool.QueueUserWorkItem
for (int i = 0; i < 4; i++)
{
//创建委托 WaitCallback
WaitCallback myWaitCallback = new WaitCallback(WorkItem);
ThreadPool.QueueUserWorkItem(myWaitCallback, i + 1);
if (i == 2)
{
goto lbGOtoThread;
}
Thread.Sleep(1000);
}
Console.WriteLine("******************");
lbGOtoThread: for (int i = 0; i < 4; i++)
{
ThreadPool.QueueUserWorkItem
(new WaitCallback(ShortWorkItem), i + 1);
Thread.Sleep(1000);
}
Console.WriteLine("***************");
for (int i = 0; i < 4; i++)
{
ThreadPool.QueueUserWorkItem
(new WaitCallback(LongWorkItem), i + 1);
//暂停线程1秒
Thread.Sleep(1000);
}
Console.ReadLine();
}
public static void WorkItem(object i)
{
string itemName;
itemName = "使用的线程编号Thread ID# = " +
Thread.CurrentThread.GetHashCode();
Console.WriteLine
("这是第1组被排入队列的第{0} 个工作,{1}", i, itemName);
Console.WriteLine("此工作线程结束!! ");
}
public static void ShortWorkItem(object i)
{
string itemName;
itemName = "使用的线程编号Thread ID# = " +
Thread.CurrentThread.GetHashCode();
Console.WriteLine
("这是第2组被排入队列的第{0} 个工作,{1}", i, itemName);
Console.WriteLine("此工作线程暂停2 秒!! ");
Thread.Sleep(2000);
}
public static void LongWorkItem(object i)
{
string itemName;
itemName = "使用的线程编号Thread ID# = " +
Thread.CurrentThread.GetHashCode();
Console.WriteLine
("这是第3组被排入队列的第{0} 个工作,{1}", i, itemName);
Console.WriteLine("此工作线程暂停10 秒!! ");
Thread.Sleep(10000);
}
}
控制台输出: