1. 程式人生 > >C#開執行緒

C#開執行緒

//引用地址:https://www.jb51.net/article/46234.htm //使用專門的執行緒類(常用) //使用執行緒類可以有多個引數與多個返回值,十分靈活! 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); } }