傳參方式有兩種:
1、創建帶參構造方法類 傳參
2、利用Thread.start(8)直接傳參,該方法會接收一個對象,並將該對象傳遞給線程,因此在線程中啟動的方法
必須接收object類型的單個參數。
3、閉包傳參 該方法使用lambda表達式。
3.1 lambda表達式中使用任何局部變量時 ,C# 會自動生成一個類,並將該變量作為該類的一個屬性。實際上與第一種方式基本一樣,但是我們無需定義類,C#會自動編譯實現該類。
3.2 使用lambda表達式會導致一些問題,如使用多個lambda表達式中使用相同的變量,他們會共享該變量值
using System; using System.Threading; namespace testThread_Transferparameters { class Program { static void Main(string[] args) { //1 var sample = new ThreadSample(10); var threadone = new Thread(sample.CountNumbers); threadone.Name = "ThreadOne"; threadone.Start(); threadone.Join(); Console.WriteLine("------------------"); //2 var threadtwo = new Thread(count); threadtwo.Name = "threadtwo"; threadtwo.Start(8); threadtwo.Join(); Console.WriteLine("------------------"); //3 var threadthree = new Thread(() => CountNumbers(20)); threadthree.Name = "threadthree"; threadthree.Start(); threadthree.Join(); Console.WriteLine("------------------"); int i = 10; var threadfour = new Thread(() => PrintNumber(i)); i = 20; var threadfive = new Thread(() => PrintNumber(i)); threadfour.Start(); threadfive.Start(); } static void count(object iterations) { CountNumbers((int)iterations); } static void CountNumbers(int iterations) { for (int i = 1; i <= iterations; i++) { Thread.Sleep(TimeSpan.FromSeconds(0.5)); Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i); } } static void PrintNumber(int number) { Console.WriteLine(number); } } class ThreadSample { private readonly int _iterations; public ThreadSample(int iterations) { _iterations = iterations; } public void CountNumbers() { for (int i = 1; i <= _iterations; i++) { Thread.Sleep(TimeSpan.FromSeconds(0.5)); Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i); } } } }
結果如下: