需引用命名空间:using System.Threading;
static void Main(string[] args) { Thread th = new Thread(Getmsg); //设置为后台线程 th.IsBackground = true; //设置线程优先级(Highest,AboveNormal,Normal,BelowNormal,Lowest) th.Priority = ThreadPriority.Lowest; //运行线程 th.Start(); //设为同步线程 th.Join(); //终止线程 th.Abort(); //线程挂起 Thread.Sleep(3000); }
1,给线程传递数据
①:使用带ParameterizedThreadStart委托参数的Thread构造函数
class Program { static void Main(string[] args) { Dome d = new Dome { Name = "Jack" }; Thread th = new Thread(msg); th.Start(d); Console.ReadKey(); //输出:Jack } private static void msg(object o) { Dome d = (Dome)o; Console.WriteLine(d.Name); } } struct Dome { public string Name; }
②:创建一个自定义类,把线程的方法定义为实例方法
class Program { static void Main(string[] args) { Dome d = new Dome("jack", 21); Thread th = new Thread(d.msg); th.Start(); Console.ReadKey(); //输出:姓名:jack,年龄:21 } } class Dome { private string _name; private int _age; public Dome(string name, int age) { this._name = name; this._age = age; } public void msg() { Console.WriteLine("姓名:{0},年龄:{1}", _name, _age); } }