线程操作主要用到Thread类,他是定义在System.Threading.dll下。使用时需要添加这一个引用。该类提供给我们四个重载的构造函
构造函数定义:
无参数委托
[SecuritySafeCritical] public Thread(ThreadStart start); [SecuritySafeCritical] public Thread(ThreadStart start, int maxStackSize);
有一个参数object委托
[SecuritySafeCritical] public Thread(ParameterizedThreadStart start); [SecuritySafeCritical] public Thread(ParameterizedThreadStart start, int maxStackSize); // maxStackSize: // 线程要使用的最大堆栈大小(以字节为单位);如果为 0 则使用可执行文件的文件头中指定的默认最大堆栈大小。重要地,对于部分受信任的代码,如果 maxStackSize // 大于默认堆栈大小,则将其忽略。不引发异常。
一、创建没有参数传入线程
//创建没有参数的线程 Thread thread = new Thread(new ThreadStart(ThreadMethod)); //或者 //Thread thread = new Thread(ThreadMethod); thread.Start(); Console.WriteLine("代码执行完成");
//线程方法定义 public static void ThreadMethod() { Console.WriteLine("当前线程ID:{0},当前线程名称:{1}", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name); while (true) { Console.WriteLine(DateTime.Now); Thread.Sleep(1000); } }
二、创建一个参数传入object类型的线程
public static void Init() { //创建一个参数的线程 //ParameterizedThreadStart 指定传入的类型是object for (int i = 0; i < 3; i++) { Thread thread = new Thread(new ParameterizedThreadStart(ThreadMethod)); object obj = i * 10; thread.Start(obj); } } //定义线程方法 public static void ThreadMethod(object number) { int i = (int)number; while (true) { i++; Console.WriteLine("当前线程ID:{0},number={1}", Thread.CurrentThread.ManagedThreadId, i); Thread.Sleep(2000); } }
三、创建使用对象实例方法,创建多个参数传入情况的线程
public static void Init() { //创建多个传入参数的线程 for (int i = 1; i < 4; i++) { Calculator cal = new Calculator(i, i * 100); Thread thread = new Thread(new ThreadStart(cal.Add)); thread.Start(); } }
public class Calculator { public int X { get; set; } public int Y { get; set; } public Calculator(int x, int y) { this.X = x; this.Y = y; } //定义线程执行方法 public void Add() { int i = 0; while (i < 2) { i++; Console.WriteLine("当前线程ID:{0},{1}+{2}={3}", Thread.CurrentThread.ManagedThreadId, X, Y, X + Y); Thread.Sleep(1000); } } }