1.引用System.Threading名稱空間。
2.使用ThreadStart,建立不可傳遞參數執行緒。
3.使用ParameterizedThreadStart,建立可傳遞參數執行緒。
4.執行緒物件的Name屬性,可取得或設定執行緒名稱。
5.在方法內可使用Thread.CurrentThread.Name屬性,取得執行緒名稱。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TestThread
{
public class Work
{
public static void Main()
{
//--建立靜態方法執行緒,不可傳遞參數--//
//使用ThreadStart
Thread ts1 = new Thread(new ThreadStart(DoStaticWork));
//設定參數名稱
ts1.Name = "ts1";
//執行執行緒
ts1.Start();
//使用類別方法名稱
Thread ts2 = new Thread(Work.DoStaticWork);
ts2.Name = "ts2";
ts2.Start();
//--建立靜態方法執行緒,可傳遞參數,參數必須是object型別--//
//使用ParameterizedThreadStart
Thread ts3 = new Thread(new ParameterizedThreadStart(DoStaticWorkMore));
ts3.Name = "ts3";
ts3.Start(50);
//使用類別方法名稱
Thread ts4 = new Thread(Work.DoStaticWorkMore);
ts4.Name = "ts4";
ts4.Start(100);
//--建立動態方法執行緒,不可傳遞參數--//
var work = new Work();
//使用ThreadStart
Thread ts5 = new Thread(new ThreadStart(work.DoWork));
ts5.Name = "ts5";
ts5.Start();
//使用類別方法名稱
Thread ts6 = new Thread(work.DoWork);
ts6.Name = "ts6";
ts6.Start();
//--建立動態方法執行緒,可傳遞參數,參數必須是object型別--//
//使用ParameterizedThreadStart
Thread ts7 = new Thread(new ParameterizedThreadStart(work.DoWorkMore));
ts7.Name = "ts7";
ts7.Start(70);
//使用類別方法名稱
Thread ts8 = new Thread(work.DoWorkMore);
ts8.Name = "ts8";
ts8.Start(60);
Console.ReadKey();
}
public static void DoStaticWork()
{
//取得執行序名稱
string ThreadName = Thread.CurrentThread.Name;
for (int i=1;i<=30;i++)
{
Console.WriteLine(ThreadName + " DoStaticWork:" + i);
}
}
public static void DoStaticWorkMore(object max)
{
string ThreadName = Thread.CurrentThread.Name;
for (int i = 1; i <= (int)max; i++)
{
Console.WriteLine(ThreadName + " DoStaticWorkMore:" + i);
}
}
public void DoWork()
{
string ThreadName = Thread.CurrentThread.Name;
for (int i = 1; i <= 30; i++)
{
Console.WriteLine(ThreadName + " DoWork:" + i);
}
}
public void DoWorkMore(object max)
{
string ThreadName = Thread.CurrentThread.Name;
for (int i = 1; i <= (int)max; i++)
{
Console.WriteLine(ThreadName + " DoWorkMore:" + i);
}
}
}
}
沒有留言:
張貼留言