C# 多线程编程及其几种方式

1、Thread多线程编程举例

  关键字:前台线程,后台线程,线程优先级,线程休眠,线程阻塞。

 1 class MultiThreadingApplication {
 2         static void Main(string[] args) {
 3             //Thread thread1 = new Thread(new ThreadStart(Test1));
 4             Thread thread1 = new Thread(Test1);//线程传入无参数委托实例
 5             //Thread thread2 = new Thread(new ParameterizedThreadStart(Test2));//正常传递
 6             Thread thread2 = new Thread(Test2);//简化传递
 7             thread1.Name = "线程1";
 8             thread1.IsBackground = true;//设为后台线程,主线成结束后台线程自动结束;前台线程在主线程结束后继续执行才结束
 9             thread2.Name = "线程2";
10             thread1.Start();
11             thread2.Start("HelloWorld");
12             Thread thread3 = new Thread(() =>
13             {
14                 Console.WriteLine("线程3开始");
15                 Console.WriteLine("线程3阻塞5秒钟");
16                 Thread.CurrentThread.Join(TimeSpan.FromSeconds(5));
17                 Console.WriteLine("{0}的执行方法",Thread.CurrentThread.Name);
18                 Console.WriteLine("线程3结束");
19             });
20             thread3.Name = "线程3";
21             thread3.Priority = ThreadPriority.Highest;//线程优先级枚举设定,此时最高,在线程池中会优先开始
22             thread3.Start();
23             Console.WriteLine("Main()主函数线程结束");
24         }
25 
26         static void Test1() {
27             Console.WriteLine("线程1开始");
28             Console.WriteLine("线程1休眠2秒钟");
29             Thread.Sleep(2000);
30             Console.WriteLine("{0}调用的无参数方法",Thread.CurrentThread.Name);
31             Console.WriteLine(Thread.CurrentThread.Name+"结束");
32         }
33 
34         static void Test2(object s) {
35             Console.WriteLine("线程2开始");
36             Console.WriteLine("{0}调用的有参数方法,方法的参数是:{1}", Thread.CurrentThread.Name, s);
37             Console.WriteLine(Thread.CurrentThread.Name + "结束");
38         }
39     }  

猜你喜欢

转载自www.cnblogs.com/mojiejushi/p/13194341.html