using System
using System.Threading;
namespace ThreadTest
{
public class A
{
public static void B()
{
while (true)
{
Console.WriteLine("A.B is running in its own thread.");
}
}
}
public class C
{
public static void Main()
{
Thread t = new Thread(new ThreadStart(A.B));
t.Start();
Thread.Sleep(5);
t.Abort();
t.Join();
Console.WriteLine("A.B has finished");
Console.ReadLine();
}
}
}
运行后显示若干行"A.B is running in its own thread."和一行"A.B has finished";
若取消程序中的“Thread.Sleep(5);”句,则运行后只显示"A.B has finished"。
理解:如无“Thread.Sleep(5);”句,则线程oThread一开始后即被中止,根本没有执行到其中的输入字符串的代码,但增加此句后,使主线程(执行Main方法的线程)休眠(sleep)了5毫秒才执行t.Abort();,这段5毫秒的时间使t线程有时间执行了输出字符串代码,由此可见该程序运行完t.start().后,有两个并行的线程,主线程和t线程,两者各自运行,可视为并行,而主线程中有控制t线程的语句,主线程休眠5毫秒时,t线程继续运行.而如果没有休眠指令,在主线程中由于t.start()和指令的下一条就是t.Abort()和t.Join(),所以使得已经在同步运行t线程立即停止了.通过该段小程序,可以帮助我们了解多线程的概念.