using System; using System.Threading; namespace threading { public class Alpha { public void Beta() { while (true) { Console.WriteLine("Alpha.Beta is running in its own thread."); } } } public class Simple { public static int Main() { Console.WriteLine("Thread Start/Stop/JoinSample"); Alpha oAlpha = new Alpha(); Thread oThread = new Thread(new ThreadStart(oAlpha.Beta)); oThread.Start(); //oThread.Join(2); //oThread.Abort(); while (!oThread.IsAlive) Thread.Sleep(4); Thread.Sleep(3);//如果没有这句,oThread没有办法运行处结果,因为线程结束太快 oThread.Abort();//线程停止 oThread.Join(); Console.WriteLine(); Console.WriteLine("Alpha.Beta has finished"); try { Console.WriteLine("Try to restart the Alpha.Beta thread"); oThread.Start(); } catch (ThreadStateException) { Console.Write("ThreadStateException trying to restart Alpha.Beta. "); Console.WriteLine("Expected since aborted threads cannot be restarted."); Console.ReadLine(); } Console.ReadLine(); return 0; } } } 程序包含Alpha和Simple两个类,在创建线程oThread时指向Alpha.Beta()方法的初始化了ThreadStart代理(delegate)对象,当我们创建的线程oTread调用oThread.Start()方法启动时,实际上程序运行的是Alpha.Beta(): Alpha oAlpha = new Alpha(); Thread oThread = new Thread(new ThreadStart(oAlpha.Beta)); oThread.Start(); 所用的线程都是依附于Main()函数所在的线程,Main()函数是C#程序的入口,起始线程称为主线程。如果所有的前台线程都停止了,那么主线程可以终止,而所有的后台线程都将无条件终止。所有的线程虽然在微观上是串行执行的,但是在宏观上可以认为他们是并行执行。 Thread.ThreadState属性 这个属性代表了线程运行时状态,在不同的情况下有不同的值,我们有时候可以通过对该值的判断来设计程序流程。 ThreadState属性的取值如下: Aborted:线程已停止; AbortRequested:线程的Thread.Abort()方法已被调用,但是线程还未停止; Backgound:线程在后台执行,与属性Thread.IsBackground有关;
Running:线程正在运行; Stopped:线程已经被停止; StopRequested:线程正在被要求停止; Suspended:线程已经被挂起(此状态下,可以通过调用Resume()方法重新运行); SuspendRequested:线程正在要求被挂起,但是未来得及响应; Unstarted:未调用Thread.Start()开始线程运行。 WaitSleepJoin:线程因为调用了Wait(),Sleep(),Join()等方法处于封锁状态; |
|
来自: 昵称10504424 > 《C#》