Thread(ThreadStart)构造函数用于初始化Thread类的新实例。如果参数的值为null,则此构造方法将提供ArgumentNullException。
句法:
public Thread(ThreadStart start);
在这里, ThreadStart是一个委托,代表当该线程开始执行时要调用的方法。
下面的程序说明了Thread(ThreadStart)构造函数的用法:
范例1:
// C# program to illustrate the
// use of Thread(ThreadStart)
// constructor with static method
using System;
using System.Threading;
// Driver Class
class GFG {
// Main Method
public static void Main()
{
// Creating and initializing a thread
// with Thread(ThreadStart) constructor
Thread thr = new Thread(new ThreadStart(Job));
thr.Start();
}
// Static method
public static void Job()
{
Console.WriteLine("Number is :");
for (int z = 0; z < 4; z++) {
Console.WriteLine(z);
}
}
}
输出:
Number is :
0
1
2
3
范例2:
// C# program to illustrate the
// use of Thread(ThreadStart)
// constructor with Non-static method
using System;
using System.Threading;
class GThread {
// Non-static method
public void Job()
{
for (int z = 0; z < 3; z++) {
Console.WriteLine("HELLO...!!");
}
}
}
// Driver Class
public class GFG {
// Main Method
public static void Main()
{
// Creating object of GThread class
GThread obj = new GThread();
// Creating and initializing a thread
// with Thread(ThreadStart) constructor
Thread thr = new Thread(new ThreadStart(obj.Job));
thr.Start();
}
}
输出:
HELLO...!!
HELLO...!!
HELLO...!!
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.thread.-ctor?view=netframework-4.7.2#System_Threading_Thread__ctor_System_Threading_ThreadStart_