主线程与子线程之间的关系
**默认情况,在新开启一个子线程的时候,他是前台线程,只有,将线程的IsBackground属性设为true;他才是后台线程
*当子线程是前台线程,则主线程结束并不影响其他线程的执行,只有所有前台线程都结束,程序结束
*当子线程是后台线程,则主线程的结束,会导致子线程的强迫结束
(个人理解,这样设计的原因:因为后台线程一般做的都是需要花费大量时间的工作,如果不这样设计,主线程已经结束,而后台工作线程还在继续,第一有可能使程序陷入死循环,第二主线程已经结束,后台线程即时执行完成也已经没有什么实际的意义)
实例代码:
**默认情况,在新开启一个子线程的时候,他是前台线程,只有,将线程的IsBackground属性设为true;他才是后台线程
*当子线程是前台线程,则主线程结束并不影响其他线程的执行,只有所有前台线程都结束,程序结束
*当子线程是后台线程,则主线程的结束,会导致子线程的强迫结束
(个人理解,这样设计的原因:因为后台线程一般做的都是需要花费大量时间的工作,如果不这样设计,主线程已经结束,而后台工作线程还在继续,第一有可能使程序陷入死循环,第二主线程已经结束,后台线程即时执行完成也已经没有什么实际的意义)
实例代码:
static Thread Mainthread; //静态变量,用来获取主线程
static void Main(string[] args)
{
Mainthread= Thread.CurrentThread;//获取主线程
Test1();
}
static void Main(string[] args)
{
Mainthread= Thread.CurrentThread;//获取主线程
Test1();
}
private static void Test1()
{
Console.WriteLine("在主进程中启动一个线程!");
{
Console.WriteLine("在主进程中启动一个线程!");
Thread firstChild = new Thread(new
ParameterizedThreadStart(ThreadProc));//threadStart 是一个委托,代表一个类型的方法
firstChild.Name = "线程1";
firstChild.IsBackground=true;
firstChild.Name = "线程1";
firstChild.IsBackground=true;
firstChild.Start(firstChild.Name);//启动线程
Thread secondChild = new Thread(new ParameterizedThreadStart(ThreadProc));
secondChild.Name = "线程2";
secondChild.IsBackground=false
secondChild.Name = "线程2";
secondChild.IsBackground=false
secondChild.Start(secondChild.Name);
Console.WriteLine("主线程结束");
Console.WriteLine(Mainthread.ThreadState);
Mainthread.Abort();
}
private static void ThreadProc(object str)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(Mainthread.ThreadState);
Console.Write(str+"调用ThreadProc: " + i.ToString() + "\r\n");
if (i == 9)
Console.WriteLine(str + "结束");
Thread.Sleep(10000);//线程被阻塞的毫秒数。0表示应挂起此线程以使其他等待线程能够执行
}
}
Console.WriteLine("主线程结束");
Console.WriteLine(Mainthread.ThreadState);
Mainthread.Abort();
}
private static void ThreadProc(object str)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(Mainthread.ThreadState);
Console.Write(str+"调用ThreadProc: " + i.ToString() + "\r\n");
if (i == 9)
Console.WriteLine(str + "结束");
Thread.Sleep(10000);//线程被阻塞的毫秒数。0表示应挂起此线程以使其他等待线程能够执行
}
}
备注:当把IsBackground 都设为true,则程序一闪而过,证明:主线程结束不管子线程结束不结束
当把IsBackground 有false
时,程序会继续正常运行。