关于线程池的一段代码
晚上睡醒了没事干,想到一个测试线程池可用线程数量的方法,本来觉得挺简单的,可是测试的时候,却发现了一个有趣的现象,发现我对线程池的理解一直有偏差。下面我放上我测试的一段小代码。
Code
class Class13
{
//这个方法如果注释掉,程序的执行会有差异,注意观察输出结果。
static Class13()
{
ThreadPool.SetMaxThreads(50, 1000);
ThreadPool.SetMinThreads(50, 1000);
}
static void Main()
{
while (true)
{
int code = Console.Read();
if (code == 49) //键盘数字1。
{
Console.Clear();
Test();
}
}
}
static void Test()
{
int workThreads = 0;
int completionPortThreads = 0;
int item = 0;
for (int i = 0; i < 100; i++)
{
//获取可用线程数和异步IO数量
ThreadPool.GetAvailableThreads(out workThreads, out completionPortThreads);
while (workThreads <= 10)
{
Console.WriteLine("线程池中已用完40个线程:当前可用线程数量:" + workThreads);
//睡眠1秒钟
Thread.Sleep(100);
ThreadPool.GetAvailableThreads(out workThreads, out completionPortThreads);
continue;
}
int ii = item++;
Console.WriteLine("可用线程数:" + workThreads + " item数量为:" + ii);
ThreadPool.QueueUserWorkItem(delegate(object sender)
{
Thread.Sleep(20);
Console.WriteLine("当前执行的任务为:" + ii);
}, null);
Thread.Sleep(0);
}
}
}
class Class13
{
//这个方法如果注释掉,程序的执行会有差异,注意观察输出结果。
static Class13()
{
ThreadPool.SetMaxThreads(50, 1000);
ThreadPool.SetMinThreads(50, 1000);
}
static void Main()
{
while (true)
{
int code = Console.Read();
if (code == 49) //键盘数字1。
{
Console.Clear();
Test();
}
}
}
static void Test()
{
int workThreads = 0;
int completionPortThreads = 0;
int item = 0;
for (int i = 0; i < 100; i++)
{
//获取可用线程数和异步IO数量
ThreadPool.GetAvailableThreads(out workThreads, out completionPortThreads);
while (workThreads <= 10)
{
Console.WriteLine("线程池中已用完40个线程:当前可用线程数量:" + workThreads);
//睡眠1秒钟
Thread.Sleep(100);
ThreadPool.GetAvailableThreads(out workThreads, out completionPortThreads);
continue;
}
int ii = item++;
Console.WriteLine("可用线程数:" + workThreads + " item数量为:" + ii);
ThreadPool.QueueUserWorkItem(delegate(object sender)
{
Thread.Sleep(20);
Console.WriteLine("当前执行的任务为:" + ii);
}, null);
Thread.Sleep(0);
}
}
}