- 利用建構子的方式,new class時把參數帶入
- 利用Start接收object單個參數的方式傳遞參數
- 利用lambda表達式調用方法
以下為執行結果
以下為程式碼:
using System;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
/** *******************
* Thread的傳遞參數
* ********************/
//方法一:使用建構子方式
var sample = new ThreadSample(3);
var threadOne = new Thread(sample.CountNumbers);
threadOne.Name = "One";
threadOne.Start();
threadOne.Join();
//方法二:利用Start接收object單個參數的方式傳遞參數,裡頭再去轉型
var threadTwo = new Thread(Count);
threadTwo.Name = "Two";
threadTwo.Start(4);
threadTwo.Join();
//方法三:利用lambda表達式
var threadThree = new Thread(() => CountNumbers(5));
threadThree.Name = "Three";
threadThree.Start();
threadThree.Join();
//觀察列印出來的值會發現都是20
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 PrintNumber(int number)
{
Console.WriteLine(number);
}
static void CountNumbers(int iterations)
{
for (int i = 0; i <= iterations; i++)
{
Thread.Sleep(TimeSpan.FromSeconds(0.5));
Console.WriteLine($"{Thread.CurrentThread.Name} prints {i}");
}
}
}
class ThreadSample
{
private readonly int _iterations;
public ThreadSample(int iterations)
{
_iterations = iterations;
}
public void CountNumbers()
{
for(int i=0;i<= _iterations;i++)
{
Thread.Sleep(TimeSpan.FromSeconds(0.5));
Console.WriteLine($"{Thread.CurrentThread.Name} prints {i}");
}
}
}
}
沒有留言:
張貼留言