线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元。一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈组成。另外,线程是进程中的一个 实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其它线程共享进程所拥有 的全部资源。一个线程可以创建和撤消另一个线程,同一进程中的多个线程之间可以并发执行。由于线程之间的相互制约,致使线程在运行中呈现出间断性。线程也 有就绪、阻塞和运行三种基本状态。每一个程序都至少有一个线程,若程序只有一个线程,那就是程序本身。
线程是程序中一个单一的顺序控制流程。在单个程序中同时运行多个线程完成不同的工作,称为多线程。
一,
1,下面一个简单的例子,
1 static void Main(string[] args) 2 { 3 //这里Thread 示例需要是 ThreadStart类型委托,委托可以直接指向方法,编译器会自动变成这样(new ThreadStart(show)) 4 Thread th = new Thread(show); 5 th.Start(); 6 } 7 8 public static void show() 9 { 10 Console.WriteLine("你好啊"); 11 }
2,线程池的使用
1 /// <summary> 2 /// 结构体 3 /// </summary> 4 public struct StateInfo 5 { 6 public List<int> list; 7 public ManualResetEvent ManualResetEvent; 8 } 9 10 static void Main(string[] args) 11 { 12 var count = 3; 13 //参数 14 StateInfo stateInfo; 15 List<int> listarry = new List<int>() { 1, 2, 3 }; 16 var manualEvents = new ManualResetEvent[count]; 17 for (int i = 0; i < count; i++) 18 { 19 stateInfo = new StateInfo(); 20 stateInfo.list = listarry; 21 stateInfo.ManualResetEvent = manualEvents[i] = new ManualResetEvent(false); 22 23 //压入线程池 24 ThreadPool.QueueUserWorkItem(new WaitCallback(PooledFunc), stateInfo); 25 } 26 27 //等待线程全部完成 28 WaitHandle.WaitAll(manualEvents); 29 30 Console.ReadLine(); 31 } 32 33 static object locker = new object(); 34 static void PooledFunc(object state) 35 { 36 var stateInfo = (StateInfo)state; 37 38 lock (locker) 39 { 40 foreach (var item in stateInfo.list) 41 { 42 Console.WriteLine(item); 43 } 44 } 45 }