线程的基本操做
线程的基本操做包括:建立线程、暂停线程、线程等待、终止线程。git
1 /*----------------------------------------------------------------------- 2 written by helio, 2019 3 ThreadSample1 4 -----------------------------------------------------------------------*/ 5 using System; 6 using System.Threading; 7 8 namespace ThreadSample 9 { 10 class Program 11 { 12 static void FirstPrintNumbsers() 13 { 14 Console.WriteLine("{0} starting..", Thread.CurrentThread.Name); 15 for (int i = 1; i <= 10; i++) 16 { 17 Console.WriteLine(i); 18 Thread.Sleep(TimeSpan.FromMilliseconds(100)); 19 } 20 } 21 22 static void SecondPrintNumbers() 23 { 24 Console.WriteLine("{0} starting...", Thread.CurrentThread.Name); 25 for (int i = 1; i <= 10; i++) 26 { 27 Console.WriteLine(i); 28 Thread.Sleep(TimeSpan.FromMilliseconds(100)); 29 } 30 } 31 static void Main(string[] args) 32 { 33 Thread t1 = new Thread(FirstPrintNumbsers); 34 Thread t2 = new Thread(SecondPrintNumbers); 35 t1.Name = "Thread1"; 36 t2.Name = "Thread2"; 37 t1.Start(); 38 t2.Start(); 39 t1.Join(); 40 t2.Join(); 41 42 Thread.CurrentThread.Name = "MainThread"; 43 FirstPrintNumbsers(); 44 Console.ReadKey(); 45 } 46 } 47 }
工做原理
在Main方法外定义了方法FristPrintNumbers、SecondPrintNumbers,该方法会被主程序和向建立的两个线程Thread一、Thread2使用。建立完成线程后,使用Start方法启动线程,使用Join方法值线程执行完成后继续执行主线程或者该线程下面的线程。github
前台线程和后台线程spa
1 ``` 2 /*----------------------------------------------------------------------- 3 written by helio, 2019 4 ThreadSample2 5 -----------------------------------------------------------------------*/ 6 using System; 7 using System.Threading; 8 9 namespace ThreadSample 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 var sampleForeground = new ThreadSample(10); 16 var sampleBackground = new ThreadSample(20); 17 18 var ThreadOne = new Thread(sampleForeground.CountNumbers); 19 ThreadOne.Name = "ForegourndThread"; 20 var ThreadTwo = new Thread(sampleBackground.CountNumbers); 21 ThreadTwo.Name = "BackgroundThread"; 22 ThreadTwo.IsBackground = true; 23 24 ThreadOne.Start(); 25 ThreadTwo.Start(); 26 } 27 28 class ThreadSample 29 { 30 private readonly int m_iteration; 31 32 public ThreadSample(int iteration) 33 { 34 m_iteration = iteration; 35 } 36 37 public void CountNumbers() 38 { 39 for (int i = 0; i < m_iteration; i++) 40 { 41 Thread.Sleep(TimeSpan.FromSeconds(0.5)); 42 Console.WriteLine("{0} prints {1}", 43 Thread.CurrentThread.Name, i); 44 } 45 } 46 } 47 } 48 } 49 ```
工做原理线程
当主程序启动时定义了两个不一样的线程。默认状况下,显示建立的线程是前台线程。经过手动设置ThradTow对象的IsBackkgournd来建立一个后台线程。<br/>
当一个程序中的前台线程完成工做后,程序就会关闭,即便还有未完成工做的后台线程。因此在上述程序中,前台线程Thread1完成工做后程序就会别关闭。code
阅读原文可访问个人我的博客对象