先看个例子:
using System;
using System.Threading;
namespace ThreadExample
{
class c2
{
static void Main()
{
Thread t1 = new Thread( ThreadFun2 )
{ Name = "Thread1", IsBackground = true };
t1.Start();
Console.WriteLine( "Main thread ending now." );
Thread.Sleep( 6000 );
Thread t2 = new Thread( ThreadFun2 )
{ Name = "Thread2", IsBackground = true };
t2.Start();
}
static void ThreadFun2()
{
Console.WriteLine( "Thread {0} started.", Thread.CurrentThread.Name );
Thread.Sleep( 3000 );
Console.WriteLine( "Thread {0} completed.", Thread.CurrentThread.Name );
}
}
}
运行结果:
Main thread ending now.
Thread Thread1 started.
Thread Thread1 completed.
Thread Thread2 started.
t1线程起来后,前台线程还没结束,所以t1的信息都打了出来,t2起来后,前台线程刚好结束,t2也被强行中止,所以t2只输出了一行信息。
去掉下面这行代码再试试:
Thread.Sleep( 6000 );
运行了3次的结果:
D:\>ThExa2.exe
Main thread ending now.
Thread Thread1 started.
D:\>ThExa2.exe
Main thread ending now.
Thread Thread1 started.
Thread Thread2 started.
D:\>ThExa2.exe
Main thread ending now.
Thread Thread1 started.
Thread Thread2 started.
第一次运行,前台线程结束时,t1只输出一行信息,t2还没输出信息就被结束。
后2次运行,t2只输出一行信息,在sleep期间,刚好前台线程结束,2个后台线程被迫结束,再无信息输出。