一:Thread的使用
我们知道这个类代表处理器线程,在Thread中有几个比较常用和重要的方法。
<1> sleep: 这个算是最简单的了。
<2> join: 这个可以让并发行处理变成串行化,什么意思呢?上代码说话最清楚。
1 class Test 2 { 3 static void Main() 4 { 5 Thread t = new Thread(Run); 6 7 t.Start(); 8 9 //Join相当于把Run方法内嵌如此 10 t.Join(); 11 12 //该死的t.Join(),害的我主线程必须在你执行完后才能执行。 13 Console.WriteLine("我是主线程:" + Thread.CurrentThread.GetHashCode()); 14 } 15 16 static void Run() 17 { 18 //等待5s 19 Thread.Sleep(5000); 20 21 Console.WriteLine("我是线程:" + Thread.CurrentThread.GetHashCode()); 22 } 23 }
<3> Interrupt和Abort:这两个关键字都是用来强制终止线程,不过两者还是有区别的。
① Interrupt: 抛出的是 ThreadInterruptedException 异常。
Abort: 抛出的是 ThreadAbortException 异常。
② Interrupt:如果终止工作线程,只能管到一次,工作线程的下一次sleep就管不到了,相当于一个
contine操作。
Abort:这个就是相当于一个break操作,工作线程彻底死掉。
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Console.WriteLine("我是主线程:" + Thread.CurrentThread.GetHashCode()); 6 Thread t = new Thread(new ThreadStart(Run)); 7 t.Start(); 8 t.Interrupt(); 9 Console.WriteLine("我是主线程:" + Thread.CurrentThread.GetHashCode()); 10 Console.ReadLine(); 11 } 12 static void Run() 13 { 14 Console.WriteLine("我是线程:" + Thread.CurrentThread.GetHashCode()); 15 for (int i = 1; i <= 3; i++) 16 { 17 Stopwatch watch = new Stopwatch(); 18 try 19 { 20 watch.Start(); 21 Console.WriteLine("我是线程:" + Thread.CurrentThread.GetHashCode()); 22 Thread.Sleep(2000); 23 watch.Stop(); 24 Console.WriteLine("第{0}延迟执行:{1}ms", i, watch.ElapsedMilliseconds); 25 } 26 catch (ThreadInterruptedException e) 27 { 28 Console.WriteLine("第{0}延迟执行:{1}ms,抛出异常", i, watch.ElapsedMilliseconds); 29 } 30 } 31 } 32 }
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Console.WriteLine("我是主线程:" + Thread.CurrentThread.GetHashCode()); 6 Thread t = new Thread(new ThreadStart(Run)); 7 t.Start(); 8 t.Abort(); 9 Console.WriteLine("我是主线程:" + Thread.CurrentThread.GetHashCode()); 10 Console.ReadLine(); 11 12 } 13 static void Run() 14 { 15 Console.WriteLine("我是线程:" + Thread.CurrentThread.GetHashCode()); 16 for (int i = 1; i <= 3; i++) 17 { 18 Stopwatch watch = new Stopwatch(); 19 try 20 { 21 watch.Start(); 22 Console.WriteLine("我是线程:" + Thread.CurrentThread.GetHashCode()); 23 Thread.Sleep(2000); 24 watch.Stop(); 25 Console.WriteLine("第{0}延迟执行:{1}ms", i, watch.ElapsedMilliseconds); 26 } 27 catch (ThreadInterruptedException e) 28 { 29 Console.WriteLine("第{0}延迟执行:{1}ms,抛出异常", i, watch.ElapsedMilliseconds); 30 } 31 } 32 } 33 }
时间: 2024-11-10 08:14:38