虽然static关键字使得只有一个Thread句柄,但每次new操作都会创建一个线程。并不能保证只创建一个线程。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
public static Thread thread;
static void Main(string[] args)
{
for(int i=0;i<5;i++)
{
thread = new Thread(ThreadFunction);
thread.IsBackground = true;
thread.Name = "Thread"+i.ToString();
thread.Start(thread);
}
while(true)
{
Console.WriteLine("Main");
Thread.Sleep(1000);
}
}
public static void ThreadFunction(Object obj)
{
Thread thread = obj as Thread;
while(true)
{
Console.WriteLine(thread.Name);
Thread.Sleep(1000);
}
}
}
}