1.使用多线程的几种方式
(1)不需要传递参数,也不需要返回参数
ThreadStart是一个委托,这个委托的定义为void ThreadStart(),没有参数与返回值。
class Program { static void Main(string[] args) { for (int i = 0; i < 20; i++) { ThreadStart threadStart = new ThreadStart(Calculate); Thread thread = new Thread(threadStart); thread.Start(); Console.WriteLine("主:" + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + ":" + DateTime.Now.Millisecond); thread.Join();//等待线程结束再进行下次循环 } Thread.Sleep(2000); Console.Read(); } public static void Calculate() { DateTime time = DateTime.Now;//得到当前时间 Random ra = new Random();//随机数对象 //Thread.Sleep(ra.Next(100, 2000));//随机休眠一段时间 Console.WriteLine("线:"+DateTime.Now.Hour+":"+DateTime.Now.Minute+":"+ DateTime.Now.Second+":"+DateTime.Now.Millisecond); } }
(2)需要传递单个参数
ParameterThreadStart委托定义为void ParameterizedThreadStart(object state),有一个参数但是没有返回值。
class Program { static void Main(string[] args) { for (int i = 0; i < 30; i++) { ParameterizedThreadStart tStart = new ParameterizedThreadStart(Calculate); Thread thread = new Thread(tStart); thread.Start(i * 10 + 10);//传递参数 } Thread.Sleep(2000); Console.Read(); } public static void Calculate(object arg) { Random ra = new Random();//随机数对象 Thread.Sleep(ra.Next(10, 100));//随机休眠一段时间 Console.WriteLine(arg); } }
(3)使用专门的线程类(常用)
使用线程类可以有多个参数与多个返回值,十分灵活!
class Program { static void Main(string[] args) { MyThread mt = new MyThread(100); ThreadStart threadStart = new ThreadStart(mt.Calculate); Thread thread = new Thread(threadStart); thread.Start(); //等待线程结束 while (thread.ThreadState != ThreadState.Stopped) { Thread.Sleep(10); } Console.WriteLine(mt.Result);//打印返回值 Console.Read(); } } public class MyThread//线程类 { public int Parame { set; get; }//参数 public int Result { set; get; }//返回值 //构造函数 public MyThread(int parame) { this.Parame = parame; } //线程执行方法 public void Calculate() { Random ra = new Random();//随机数对象 Thread.Sleep(ra.Next(10, 100));//随机休眠一段时间 Console.WriteLine(this.Parame); this.Result = this.Parame * ra.Next(10, 100); } }
(4)使用匿名方法(常用)
使用匿名方法启动线程可以有多个参数和返回值,而且使用非常方便!
class Program { static void Main(string[] args) { int Parame = 100;//当做参数 int Result = 0;//当做返回值 //匿名方法 ThreadStart threadStart = new ThreadStart(delegate() { Random ra = new Random();//随机数对象 Thread.Sleep(ra.Next(10, 100));//随机休眠一段时间 Console.WriteLine(Parame);//输出参数 Result = Parame * ra.Next(10, 100);//计算返回值 }); Thread thread = new Thread(threadStart); thread.Start();//多线程启动匿名方法 //等待线程结束 while (thread.ThreadState != ThreadState.Stopped) { Thread.Sleep(10); } Console.WriteLine(Result);//打印返回值 Console.Read(); } }