class CustomThreadPool
{
//仅仅只是计数
public static int count;
public static Thread QueueUserWorkItem(Action<object> action)
{
return QueueUserWorkItem(action, null);
}
public static Thread QueueUserWorkItem(Action<object> action, object state)
{
Random r = new Random();
if (r.Next(1, 10) < 4)
{
count++;
var th = new Thread(() =>
{
Console.WriteLine("我在忙,等会处理你的事情");
Thread.Sleep(2000);
action(state);
});
th.Start();
return th;
}
else
{
var th = new Thread(() => action(state));
th.Start();
return th;
}
}
}
static void Main(string[] args)
{
Thread[] thArr;
while (true)
{
thArr = new Thread[5];
for (int i = 0; i < 5; i++)
{
if (i % 2 == 0)
{
thArr[i] = CustomThreadPool.QueueUserWorkItem(s => Console.WriteLine("当前参数是:{0}", s), i.ToString());
}
else
{
thArr[i] = CustomThreadPool.QueueUserWorkItem(s => Console.WriteLine("当前参数是:{0}", s));
}
}
//等待线程执行完毕
for (int i = 0; i < 5; i++)
{
thArr[i].Join();
}
if (CustomThreadPool.count == 0)
{
Console.WriteLine("RP非常不错");
}
CustomThreadPool.count = 0;
Console.WriteLine("按回车键继续");
Console.ReadLine();
}
}