避免线程过多
下面的例子中创建了 201 个线程,用 VS 直接运行了 1 个小时还是只有第一个时间输出到了控制台,只好手动停了。
cs
using System;
using System.Threading;
namespace TooMuchThread
{
class Program
{
static void Main(string args)
{
Console.WriteLine(DateTime.Now.ToString());
for (int i = 0; i < 200; i++)
{
Thread t = new Thread(() =>
{
int j = 1;
while (true)
{
j++;
}
});
t.IsBackground = true;
t.Start();
}
Thread.Sleep(5000);
Thread t201 = new Thread(() => {
while (true)
{
Console.WriteLine("T201 正在执行");
}
});
t201.Start();
Console.WriteLine(DateTime.Now.ToString());
Console.ReadKey();
}
}
}