我们在创建或销毁一个线程时需要一定的内存开销,过多的使用线程会造成内存资源的浪费。为了解决这一问题,引入了线程池的概念。
线程池里的线程是怎么工作的呢?当应用程序需要创建线程时,线程池会初始化一个线程,这个线程和其他的线程一样,但是使用完后不会自行销毁,而是以挂起的状态,回到线程池中,当应用程序再次对线程池发出请求时,线程池里挂起的线程会再度被激活。这样可以减少创建或销毁一个线程时需要的内存开销。线程池里的线程时后台线程,每个线程所占内存大小约1M
当应用程序需要线程时,需要调用QueueUserWorkItem()方法将对应的任务添加到线程池中,线程池会从队列中提取任务,并且将其委派给线程池的线程执行。
下面看这个例子
static void Worker()
{
int count = 0;
count++;
}
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
Thread thread = new Thread(Worker);
thread.Start();
}
sw.Stop();
Console.WriteLine("运行创建线程时所需要的时间:" + sw.ElapsedMilliseconds);
sw.Restart();
for (int i = 0; i < 1000; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(s =>
{
int count = 0;
count++;
//Console.WriteLine("当前线程ID:" + Thread.CurrentThread.ManagedThreadId);
}));
}
sw.Stop();
Console.WriteLine("创建线程池所需要的时间:"+sw.ElapsedMilliseconds);
Console.ReadKey();
}
结果:
ThreadPool.QueueUserWorkItem(new WaitCallback(s =>
{
int count = 0;
count++;
Console.WriteLine("当前线程ID:" + Thread.CurrentThread.ManagedThreadId);
}));
把这个注释取消掉,再看结果。
使用线程池可以发现只有线程池中的几个线程被重复利用。大大提高了程序的效率。
- QueueUserWorkItem方法还有两个参数的重载
public static bool QueueUserWorkItem(WaitCallback callBack, object state);
第一个参数为线程池执行的回调方法,第二个参数表示传递给回调方法的参数。
static void Main(string[] args)
{
Console.WriteLine("主线程ID={0}",Thread.CurrentThread.ManagedThreadId);
ThreadPool.QueueUserWorkItem(CallBackItem);
ThreadPool.QueueUserWorkItem(CallBackItem, "Worker");
Console.ReadKey();
}
static void CallBackItem(object state)
{
Console.WriteLine("子线程执行");
if (state != null)
{
Console.WriteLine("ID = {0}:{1}", Thread.CurrentThread.ManagedThreadId, state.ToString());
}
else
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
还可以传递复杂一些的参数,比如一个实体类的参数。
先写一个简单的实体类
public class Worker
{
public string name { get; set; }
public int age { get; set; }
}
在写两个输出的方法
public class Ex
{
public void Worker1(object state)
{
string name = state as string;
Console.WriteLine("chlid thread working...");
Console.WriteLine("name is" + name);
Console.WriteLine("child thread's Id is " + Thread.CurrentThread.ManagedThreadId.ToString());
}
public void Worker(object state)
{
Worker w1 = (Worker)state;
Console.WriteLine("child thread working...");
Console.WriteLine("name is " + w1.name);
Console.WriteLine("age is " + w1.age);
Console.WriteLine("child thread's Id is " + Thread.CurrentThread.ManagedThreadId.ToString());
}
}
在主方法中实例化类和使用线程池。
static void Main(string[] args)
{
Ex ex = new Ex();
ThreadPool.QueueUserWorkItem(ex.Worker1);
ThreadPool.QueueUserWorkItem(ex.Worker1, "李四");
Worker worker = new Worker();
worker.name = "张三";
worker.age = 21;
ThreadPool.QueueUserWorkItem(ex.Worker,worker);
Console.WriteLine("Main thread working...");
Console.WriteLine("Main thread's Id is " + Thread.CurrentThread.ManagedThreadId.ToString());
Console.ReadKey();
}