使用Thread
类的Name
属性来更改或获取线程的名称。下面我们来看一个例子,演示如何设置和获取线程的名称。
using System
using System.Threading
public class MyThread
{
public void Thread1()
{
for(int i=0 i<5 i++)
{
Thread t = Thread.CurrentThread
Console.WriteLine(t.Name + " is running at :"+i)
}
}
}
public class ThreadExample
{
public static void Main()
{
MyThread mt = new MyThread()
Thread t1 = new Thread(new ThreadStart(mt.Thread1))
Thread t2 = new Thread(new ThreadStart(mt.Thread1))
Thread t3 = new Thread(new ThreadStart(mt.Thread1))
t1.Name = "Thread1"
t2.Name = "Thread2"
t3.Name = "Thread3"
t1.Start()
t2.Start()
t3.Start()
}
}
执行上面示例代码,得到以下结果 -
Thread1 is running at :0
Thread2 is running at :0
Thread3 is running at :0
Thread3 is running at :1
Thread3 is running at :2
Thread3 is running at :3
Thread3 is running at :4
Thread2 is running at :1
Thread2 is running at :2
Thread2 is running at :3
Thread2 is running at :4
Thread1 is running at :1
Thread1 is running at :2
Thread1 is running at :3
Thread1 is running at :4