.NET框架是C#的運行時類庫,.NET是一個多線程的環境。線程(Thread)是進程中一個單一的順序控制流程。線程是進程中的實體。一個進程可以有多個線程,一個線程必須有一個父進程。
線程一般具有read,blocking和operation三種基本狀態。由三種基本狀態,衍化出五種線程的基本操作。首先,derive,線程是在進程內派生出來的。其次,schedule,選擇一個ready的線程進入operation狀態。第三,block,如果一個線程在執行過程中需要等待某個事件發生則被阻塞。第四,unblock,如果事件開始,則該線程被unblock,進入ready隊列。第五,finish,線程結束,它執行過的寄存器上下文及堆棧內容會被釋放。
新線程是新產生的線程對象,它還沒有分配資源。因此只能用start()或close()方法。
Runable狀態就是線程在start()方法運行后,得到線程所必需資源並且調用run()方法執行。
Not Runable非運行狀態是發生以下事件而進入的狀態,suspend()方法被調用,sleep()方法被調用,線程使用wait()來等待條件變量,線程處於I/O等待。
Dead是當Run()方法返回,或別的線程調用stop()方法,線程進入Dead狀態。下邊是Thread的兩個簡單例子。
Using System; using System.Threading; public class SimpleThread { public void Method() { int i = 1,j = 2; int result = i + j ; Console.WriteLine("thread{0} Value{1}", AppDomain.GetCurrentThreadId().ToString, result.ToString()); } static void Main() { SimpleThread thread1 = new SimpleThread(); thread1.Method(); ThreadStart ts = new ThreadStart(thread1.Method); Thread t = new Thread(ts); t.Start(); Console.ReadLine(); } }
1 using System; 2 using System.Threading; 3 4 public class ThreadExample 5 { 6 public static void ThreadProc() 7 { 8 for(int i = 0; i <10; i++) 9 { 10 Console.WriteLine("ThreadProc:{0}",i); 11 Thread.Sleep(0); 12 } 13 } 14 public static void Main() 15 { 16 Console.WriteLine("Main thread: Start a second thread."); 17 Thread t =new Thread(new ThreadStart(ThreadProc)); 18 t.Start(); 19 for(int i = 0; i < 4; i++) 20 { 21 Console.WriteLine("Main thread:Do some work."); 22 Thread.Sleep(0); 23 } 24 Console.WriteLine("Main thread:Call Join(),to wait until ThreadProc ends."); 25 t.Join(); 26 Console.WriteLine(Main thread:ThreadProc.Join has returned.Press Enter to end program."); 27 Console.ReadLine(); 28 } 29 }