在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
using System; using System.Threading; namespace ThreadTest { public class ClassSample { public void Method() { while (true) { Console.WriteLine("ClassSample中的Mehtod正在执行。"); } } } class Program { public static void Main(string[] args) { ClassSample classOne= new ClassSample(); Thread threadSample = new Thread(new ThreadStart(classOne.Method)); threadSample.Start(); while(!threadSample.IsAlive) Thread.Sleep(1); threadSample.Abort(); threadSample.Join(); Console.WriteLine(); Console.WriteLine("Class1中的Method1已经执行完毕。"); try { Console.WriteLine("尝试重新运行Class1的Method线程。"); threadSample.Start(); }catch(ThreadStateException) { Console.WriteLine("重新运行失败。"); Console.WriteLine(); } Console.ReadKey(true); } } } 注意到Thread threadSample = new Thread(new ThreadStart(classOne.Method));,所以当threadSample启动时,执行的是classOne中的Method,具体的执行流程是,在Main函数中的while循环中,使用了静态方法Thead.Sleep()让主线程休眠了一毫秒,从而执行线程threadSample。 ③最后我也要了解Thread的优先级,当CPU给不同的线程分配运行时间时,CPU是按照线程的优先级给予分配的,在C#中,线程拥有五个不同的优先级,由高到低分别是Highest、AboveNormal、Normal、BelowNormal和Lowest,可以通过下面的语句指定线程的优先级: using System; using System.Threading; namespace ThreadTest { public class ClassSample { int i; public void MethodSample() { i++; Console.WriteLine("ClassSample中的MehtodSample正在执行,此时i的值为:{0}",i); } } class Program { public static void Main(string[] args) { ClassSample classOne = new ClassSample(); Thread threadOne = new Thread(new ThreadStart(classOne.MethodSample)); threadOne.Start(); Thread.Sleep(1000); //主线程休眠1秒,执行MethodSample方法 Console.WriteLine("threadOne此时的运行状态为:{0}",threadOne.ThreadState); threadOne.Abort(); Thread threadTwo = new Thread(new ThreadStart(classOne.MethodSample)); //Console.WriteLine("threadOne此时的运行状态为:{0}",threadOne.ThreadState); //如果threadTwo还没有启动,那么ThreadOne的状态应该是AbortRequested threadTwo.Start(); Console.WriteLine("threadOne此时的运行状态为:{0}",threadOne.ThreadState); Console.WriteLine("threadTwo此时的优先级是:{0}",threadTwo.Priority); threadTwo.Priority=ThreadPriority.Highest; Console.WriteLine("threadTwo此时的优先级是:{0}",threadTwo.Priority); Console.ReadKey(true); } } }
|
请发表评论