线程池(英语:thread pool):一种线程使用模式。线程过多会带来调度开销,进而影响缓存局部性和整体性能。而线程池维护着多个线程,等待着监督管理者分配可并发执行的任务。这避免了在处理短时间任务时创建与销毁线程的代价。线程池不仅能够保证内核的充分利用,还能防止过分调度。可用线程数量应该取决于可用的并发处理器、处理器内核、内存、网络sockets等的数量。
using System;
using System.Diagnostics;
using System.Threading;
namespace ThreadDemo2
{
class Program
{
static void Main(string[] args)
{
//定义一个计时器
Stopwatch sw = new Stopwatch();
sw.Start();
int count = 0;
for (int i = 0; i < 100; i++)
{
Thread thread = new Thread(
() =>
{
count = 0;
count++;
});
thread.Start();
}
//停止计时
sw.Stop();
Console.WriteLine("运行创建花费的时间"+ sw.ElapsedMilliseconds);
//重新启动计时器
sw.Restart();
for (int i = 0; i < 100; i++)
{
//用线程池里面的方法
ThreadPool.QueueUserWorkItem(s =>
{
count = 0;
count++;
Console.WriteLine("当前线程ID"+Thread.CurrentThread.ManagedThreadId);
});
}
sw.Stop();
Console.WriteLine("运行线程池花费的时间" + sw.ElapsedMilliseconds);
Console.ReadKey();
}
}
}